Search code examples
reactjscrudmernredux-toolkit

Uncaught Error: Actions must be plain objects using redux/toolkit


Hey guys I'm using redux/toolkit, How can I update the user, Although it updates and saves on the backend, I get an error of this?

I tried using direct put in onsubmit, it works but I feel uncomfortable since it will make the code messy.

https://localhost/api/users/:id

this one works but I'd like to use redux and API calls

Submit button

const onSubmit =  async ({username, email, studentid}) => {
        let user = {username, email ,studentid}
        updateUser(id, user,dispatch) 
      }

Apicalls.js

export const updateUser = async (id,user, dispatch) =>{
  dispatch(updateStart())

  try {
    const res = await publicRequest.put(`/users/${id}`, user) 
    console.log(res.data)
    dispatch(updatenSuccess(res.data))
  } catch (error) {
    dispatch(updatenFailure)
  }
}

AuthSlice.js

export const authSlice = createSlice({
    name: 'auth',
    initialState: {
        currentUser: null,
        isFetching : false,
        isError: false,
        isSuccess: false,
    },
    reducers: {
        updateStart: (state)=>{
            state.isFetching = true;
            state.isError = false;
        },
        updateSuccess: (state, action) =>{
            state.isFetching = true;
            state.isSuccess = true;
            state.currentUser = action.payload
        },
        updateFailure: (state) =>{
            state.isFetching = false;
            state.isError = true;
        }, 
    }

})

export const {rupdateStart, updatenSuccess, updatenFailure} = authSlice.actions;
export default authSlice.reducer

Sample


Solution

  • You are most likely just dispatching undefined here, due to a typo.

    it should be updateSuccess, not updatenSuccess

    also, dispatch(updatenFailure) should be dispatch(updatenFailure())

    All that said, you are writing a lot of stuff by hand here that is already part of RTK - either in the form of createAsyncThunk or RTK Query. I would highly recommend you to go through the full official Redux Tutorial and learning those concepts before writing more code.