Reputation: 2471
I am building a react application using redux.
In the redux store, let's say I have a book object with title
, isLoading
, error
:
const bookStore = {
title: null,
isLoading: false,
error: null
}
I have two actions:
In each action, I have to handle isLoading
and error
.
In the react component I can check (we ignore the loading for now)
if (error) {return ErrorComponent}
else return BookComponent
The thing is that I want to show the errors in different ways. If the request is GET (fetch data), I want to display error as ErrorComponent. If the request is PUT (update title) I want to display the error as a Toast.
How can I do that if I only have one error property in redux store?
Should I write the code like:
const bookStore = {
title: null,
isLoading: false,
fetchError: null,
putError: null
}
But in this case I have to check like
if (fetchError) {display ErrorComponent}
else if (putError) {display Toast}
else display BookComponent
It is kind of inconvenient. What would be a better way to do this?
Upvotes: 0
Views: 90
Reputation: 597
I guess you can set error
as an object
error : { type: action.payload.type , value: action.payload.error}
And your code will be :
if (error) {
return error.type === 'error1' ? ErrorComponent : Toast; // or you can handle `toast` inside ErrorComponent
}
else { return BookComponent }
Also, you can handle disply of error messages according to type
you set in reducer.
Hope this helps!
Upvotes: 1