Home > database >  error when passing parameters to an async redux action
error when passing parameters to an async redux action

Time:07-25

I am trying to create a scraping application using redux toolkit for learning purposes but the scraping process fails whenever I pass custom parameters in the dispatch statement but works correctly on passing default parameters in the thunk My async thunk

export const loadData = createAsyncThunk(
  "alldata/getdata",
  async ({ pageNo, language }, thunkAPI) => {
    const data = await fetch(
      `http://localhost:5000/scrape?pageNo=${encodeURIComponent(
        pageNo
      )}&language=${encodeURIComponent(language)}`
    );
    const json = data.json();
    return json;
  }
);

My slice

const projectSlice = createSlice({
  name: "allprojects",
  state: {
    projectState: [],
    workingState: [],
    isLoading: false,
    hasError: false,
  },
  reducers: {
    addProject: (state, action) => {
      return state.workingState.push(action.payload);
    },
    removeProject: (state, action) => {
      return state.workingState.filter(
        (project) => project.id !== action.payload.id
      );
    },
  },
  extraReducers: {
    [loadData.pending]: (state, action) => {
      state.isLoading = true;
      state.hasError = false;
    },
    [loadData.fulfilled]: (state, action) => {
      const { json } = action.payload;
      state.isLoading = false;
      state.hasError = false;
    },
    [loadData.rejected]: (state, action) => {
      state.isLoading = false;
      state.hasError = true;
    },
  },
});

export const { addProject, removeProject } = projectSlice.actions;
export const { Projectreducer } = projectSlice.reducer;
export const selectAllPosts = (state) => state.allprojects.projectState;

Calling the async action

React.useEffect(() => {
    console.log(dispatch(loadData(1, "ruby")));
  }, []);
//url:https://github.com/search?p=undefined&q=language:undefined

how do I solve this error

CodePudding user response:

The async thunk arguments must be collected in one object:

dispatch(loadData({ pageNo: 1, language: "ruby" }))

See https://redux-toolkit.js.org/api/createAsyncThunk#payloadcreator

  • Related