Search code examples
javascriptreactjsreduceredux-toolkitredux-thunk

How can I get the id from an async thunk function to extra reducer?


// Delete thunk

export const deletePost = createAsyncThunk("deletePost", async (action) => {
  console.log("🚀 ~ deletePost ~ action", action) // here I'm 
  getting id
  const response = await deletePos(action);
  return response.data;
});

I'm dispatching id to delete specific post from the posts array. The issue is cannot get the id from async thunk to extra reducer. I want the id in extra reducer fulfilled case so I can delete the specific post from the array. Is there a way to pass action from async thunk to extra reducer?

In action I'm getting the successful message from api, but I need the id

Extra reducer

builder.addCase(deletePost.fulfilled, (state, action) => {
  console.log(action)
  state.posts = state.posts.filter((post) => post._id !== action.payload);
  state.loading = false;
});

Solution

  • It seems you should return the action value from the deletePost action. I'd suggest also renaming the parameter so it's clear to future readers what exactly that value represents.

    Example:

    export const deletePost = createAsyncThunk("deletePost", async (id) => {
      console.log("🚀 ~ deletePost ~ id", { id });
      await deletePos(id);
      return id; // <-- return id value
    });
    
    builder.addCase(deletePost.fulfilled, (state, action) => {
      state.posts = state.posts.filter((post) => post._id !== action.payload);
      state.loading = false;
    });