How to get error message in Redux toolkit?

Viewed 256

How to display default error action.message in reactjs toolkit?

Got a reducer:

...
getQueryFail: state => {
state.loading = false
state.errors = true
}
...

And actions dispatch:

...
catch(error){
dispatch (getQueryFail())
}
....

How to display error message on fail action?

1 Answers

If I'm understanding your question, it would/should be as simple as passing the error to the getQueryFail action creator. Assuming getQueryFail is a createAction action then any argument passed to it is passed in the action payload.

catch(error){
  dispatch (getQueryFail(error))
}

In the reducer access the action.payload to get the error.

getQueryFail: (state, action) => {
  state.loading = false;
  state.errors = true;
  state.error = action.payload;
}

It may be more clear to pass an object with error key though.

catch(error){
  dispatch (getQueryFail({ error }))
}

...

getQueryFail: (state, action) => {
  state.loading = false;
  state.errors = true;
  state.error = action.payload.error;
}
Related