0

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:

  1. Fetch/GET book data from server
  2. Update/PUT book title

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?

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.