0

0

I am learning react and redux toolkit , i have a user who has an array of collections , when i add a collection to that user i dispatch an action called updateUser which supposed to update the user store and then i redirect it to another component where i display the list of the collections of that user, but the new added collection does not appears unless i refresh the page . I tried so many thing and searched on internet but did not find a solution so any help please ? so this is the code in my component

const handleSubmit = async () => {
  const { data, isError, isLoading } = await addCollection({
  userId: "62e3a98b0b18ffe585142144",
  collections: selectedCollections,
});

   dispatch(updateUser({ data, isError: false, isError: false }));
   navigate("/collections_list");
};

this is the userSlice file :

export const userSlice = createSlice({
 name: "collection",
initialState,
reducers: {
appendUser: (state, action) => {
state.user = [...state.allCollections, ...action.payload.data];
state.myCollections = [
...state.myCollections,
...action.payload.myCollections,
 ];
 state.isLoading = action.payload.isLoading;
 state.isError = action.payload.isError;
},
updateUser: (state, action) => {
state.user = action.payload.data;
state.isLoading = action.payload.isLoading;
state.isError = action.payload.isError;
},
},
});

Ps: in the component where i display the list of collection i am using useSelector to get the user from the store. Please anyone can help ? i am really stuck . Thank you .

Ghost
  • 318
  • 2
  • 8

1 Answers1

-1

after trying many things i found that the solution is replacing navigate("/") with window.location.replace("/") after updating the store . I think that this is because navigate does not make the component re-render however window.location.replace does .

Ghost
  • 318
  • 2
  • 8
  • yes, but no... This might work but this is not the way to do it. Reloading the page shouldn't be necessary and goes against the whole reason of using react/react-router – Y. Gherbi Aug 08 '22 at 18:13