Home > database >  builder.addCase does not change the state & does not console log
builder.addCase does not change the state & does not console log

Time:01-25

Hello i have a very strange problem. I fetch data with the CreateAsyncThunk and receive them well but the state is not changing

const initialState = {
  posts: [],
  status: "idle", //idle | loading | success | failed
  error: null,
};

export const fetchPosts = createAsyncThunk("posts/fetchPosts", async () => {
  const response = await axios.get(POSTS_URL);
  return response.data;
});

Here is my addCase :

extraReducers: (builder) => {
  builder.addCase(fetchPosts.fulfilled, (state, action) => {
    state.status = "success";
    console.log("test")
    state.posts = action.payload;
  });
},

Here is my Redux devtools action Here is my Redux devtools state

Even the console logs inside my addCase are not showing

It looks like it dont go inside any addCase

CodePudding user response:

If the console logs inside the addCase functions are not showing, it could mean that the async thunk is not dispatching an action that the extraReducers function is listening for.

One possibility is that the async thunk is not being called at all. Make sure that the async thunk is being invoked in the component that is supposed to use the fetched data.

Another possibility is that there is an error when calling the async thunk. You can add a try-catch block around the async thunk call to see if it throws an error.

try {
      const response = await fetchPosts();
     // Do something with the response
    } catch (err) {
      console.error(err);
}

Also, make sure that the async thunk is being used in the same store where the extraReducers function is defined.

Lastly, it could be that the status and posts property you're trying to update on the state object doesn't exist, or that the component using this data is using the wrong state object. Double-check the initial state object and make sure that the properties you're trying to update exist

CodePudding user response:

Thank you for your response @vladimir but i just found what was my error....

I simply had the extraReducers INSIDE the reducers block.

And it was fixed simply by moving the extraReducers OUTSIDE the reducers block.... Newbie problem :)

  • Related