Marek Reszke
Marek Reszke

Reputation: 25

React - Ways to update state after ajax post request

Hi I'm newbie with react, and I have problem with update application state after ajax post request. For example my state looks like that:

state: {
   persons: []
}

Then I want to add new person to state, so I fetch request to serwer, and there is a question. Should I return from server updated collection to set new state, or should I return response and in request callback force new request to server to get data? Or is there other option, like listener with will update state after any response with status ok?

Upvotes: 2

Views: 4435

Answers (3)

Shubham Khatri
Shubham Khatri

Reputation: 281676

You can directly setState within the success function of ajax call.

    var self = this;
    $.ajax({
        type: 'GET',
        url: "http://localhost:9000/abc",
        dataType: 'json',
        success: function(data) {
            self.setState({persons: data});
        },
        error: function(jqXHR,textStatus,errorThrown) {
            console.log(textStatus);
        }
    });    

I have been following this method throughout my project and it works like a charm.

Upvotes: 2

Matteo Frana
Matteo Frana

Reputation: 579

your Redux action creator will fetch data from the server. You will likely have a promise from the fetch library (Axios, isomorphic fetch, ...).

You then have to use a store Middleware to handle the async action: you could use either Redux-Promise or Redux-Thunk which catch a Promise or a function of dispatch instead of a plain string action. Middlewares allow you to dispatch the plain action when you have your data available (or on error).

When you have your data available and your action called by middleware, than your Reducer would create the new state, taking the array of people from the action payload.

I suggest that you read this part of Redux documentation: http://redux.js.org/docs/advanced/AsyncActions.html

Async actions and middleware is one of the tough parts of Redux, but when you understand how middleware works, it isn't really complicated, you have just to dedicate some time to reading the Redux documentation.

Have a nice day, Matteo

Upvotes: 0

Neil Twist
Neil Twist

Reputation: 1159

I think this depends on two things for me:

  1. Do you need to be super efficient on network bandwidth and latency?
  2. Do you already have a method to do the ajax GET request and update the state?

If the answer to 1. is YES, then you need to get the data in the response from the POST and update state.

If the answer to 1. is NO, but the answer to 2. is YES, then just trigger another ajax request.

If the answer to both is NO, then I'd go with whichever looks cleaner in the code.

Another thought though, do you need to poll for the list every so often? In which case you should probably use the same method you are already using to poll.

Upvotes: 0

Related Questions