shazim ali
shazim ali

Reputation: 425

Redux toolkit reducer not receiving ( {action.payload} )

i am trying to make custom server side pagination on every click. but when i try to update state by using reducer i got this error

enter image description here

COMPONENT FILE from where i am dispatching this reducer

 function changePageByNumber(page){
      dispatch(pageByNumber({page:page})) //dispatching reducer
      dispatch(fetchUsers({page:page}));
    }

SLICE FILE

const usersSlice = createSlice({
name:'users',
initialState: usersAdapter.getInitialState( { loading: false, page: 1, total_pages: null } ),
reducers:{
  pageByNumber: (state,{action}) => {
    state.page = action.payload // why action not getting payload
  }
},
extraReducers: {
    [fetchUsers.pending]: (state) => {
      state.loading = true
    },
    [fetchUsers.fulfilled]: (state, { payload}) => {
      state.loading = false,
      state.total_records = payload.total,
      state.per_page = payload.per_page,
      state.total_pages = payload.total/payload.per_page,
      usersAdapter.setAll(state, payload.data)      
    },
    [fetchUsers.rejected]: (state) => {
      state.loading = false
    }
  },
});

export const usersSelectors = usersAdapter.getSelectors(
  (state) => state.users,
  )

export const {pageByNumber} = usersSlice.actions
export default usersSlice.reducer

Upvotes: 1

Views: 1797

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

The action object is the second argument passed to the reducer. There is no action.action so attempting to access into action.action.payload throws the error.

You should destructure the payload property from action:

pageByNumber: (state, action) => {
  state.page = action.payload;
}

or

pageByNumber: (state, { payload }) => {
  state.page = payload;
}

Based on the dispatched action dispatch(pageByNumber({ page: page })) I'd also say that you need to access the page property of the action payload:

pageByNumber: (state, action) => {
  state.page = action.payload.page;
}

Upvotes: 2

Related Questions