How to update Redux’s global status in an React application after posting to the API?

Asked

Viewed 73 times

1

An React form that you enter with name and text.

The application uses Redux global state, it pulls an Axios API and posts to the API with the form data.

When I do a new post I want to update the global status to show the post on the screen without having to load the page, only I’m not getting it. What would be the best way to do that.

1 answer

0


It seems to me that your problem is in your report, more specifically in this section:

 case TypesPost.NEW_POST:

        const newPost = state.arrayPost
        newPost.push(action.payload)

        return{
          arrayPost: newPost
        }

when you make a const newPost = state.arrayPost you are performing an assignment by reference, just when you make a push in newPost you are changing the current state of your Master, and while trying to update the state in:


        return{
          arrayPost: newPost
        }

the reference remains the same, so most likely no matter how much your array has an Input, this status change is not identified, so components are not reported.

I suggest you change your return by leaving it that way:

 case TypesPost.NEW_POST:

        const newPost = [...state.arrayPost, action.payload]

        return{
          arrayPost: newPost
        }

this way a new array will be generated with the new post.

  • Thank you Gabriel, you are a genius, thank you for asking hint and for the explanation. I’m going to ask another question about Redux from another question that arose, if you can see and help me. But thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.