redux toolkit custom selector not updating automatically

I have a custom selector:

const unlockedJobStatuses = useSelector(selectUnlockedStatuses);

I'm mapping over all the elements in said selector to generate cards. The cards have drag and drop functionality that allow the user to change the order. When handleDragEnd runs, the order of the elements should get updated in the Redux store. For some reason, though the custom selector is not updating automatically and I can only get the UI to reorder the cards correctly after a refresh. How can I resolve this:

<DragDropContext onDragEnd={handleDragEnd}>
  <Droppable droppableId='statuses'>
    {(provided) => (
      <ul className={classes.statusList} {...provided.droppableProps} ref={provided.innerRef}>
        {unlockedJobStatuses.map((status, index) => (
          <Draggable draggableId={`status-${status.id}`} key={status.id} index={index}>
            {(provided) => (
              <li {...provided.draggableProps} {...provided.dragHandleProps} ref={provided.innerRef}>
                <StatusCard
                  status={status}
                  orderChangeToggle={orderChangeToggle}
                  setOrderChangeToggle={setOrderChangeToggle}
                  handleStatusDelete={handleStatusDelete}
                />
              </li>
            )}
          </Draggable>
        ))}
        {provided.placeholder}
      </ul>
    )}
  </Droppable>
</DragDropContext>
  const handleDragEnd = async (result: DropResult) => {
    if (!result.destination || result.source.index === result.destination.index) {
      return;
    }

    const draftUnlockedJobStatuses = [...unlockedJobStatuses];
    const [movingStatus] = draftUnlockedJobStatuses.splice(result.source.index, 1);
    draftUnlockedJobStatuses.splice(result.destination.index, 0, movingStatus);

    const updatedOrder = draftUnlockedJobStatuses.map((status, index) => ({ id: status.id, newOrder: index + 1 }));

    dispatch(reorderJobStatuses({ statusUpdatesArr: updatedOrder }));
  };

This is what my async thunk looks like:

export const reorderJobStatuses = createAsyncThunk(
  'jobstatus/reorder',
  async ({ statusUpdatesArr }: any, { dispatch, rejectWithValue }) => {
    try {
      const response: any = await new JobApi().reorderStatuses({ statusUpdatesArr });
      return response;
    } catch (err) {
      handleNetworkError(dispatch, err);
      return rejectWithValue(err.response?.data?.message || err.message || 'Error');
    }
  },
);```


Read more here: https://stackoverflow.com/questions/67943854/redux-toolkit-custom-selector-not-updating-automatically

Content Attribution

This content was originally published by Jevon Cochran at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: