ericbae
ericbae

Reputation: 9644

Reactjs - getting data from server and updating

(reactjs newbie here)...

I'm using Reactjs to create a page where I have

Now, the "searchText" and "data" are my states and I'm trying to figure out how to update the "results" only after the data is received from the server.

I have an event where I handle whenever user types something as a search text

    handleUserInput: function(searchText) {
      this.loadDataFromServer(searchText);

      this.setState({
        searchText: searchText,
      });
    },

But with the above function, the following thing happens

  1. Initial data is loaded
  2. User types in something
  3. The result is IMMEDIATELY updated to only show the the result that contains the search text (code below), BUT at the same time a request is made to the server to fetch results where the result contains the search text

    this.props.products.forEach(function(product) { if(product.name.toLowerCase().indexOf(this.props.searchText) > -1) { row = rows.push(row) } }.bind(this));

  4. After about a second, new data is received from the server and the result is refreshed again.

Obviously what I want to do is

  1. Load initial data
  2. User types search text
  3. Request data from the server
  4. Receive data from the server
  5. Update the results

What is the proper way of achieving this?

Upvotes: 6

Views: 953

Answers (2)

Douglas
Douglas

Reputation: 37761

So, it is just the first refresh that you want to stop right?

If it is already refreshing once the results come from the server, it seems that all you need to do is not filter the results on the client in step 3 - then the same virtual DOM will be generated as in the first place, so the result list will only update the actual DOM once the server responds.

Upvotes: 0

viven
viven

Reputation: 27

Don't think searchText should be a state itself. You could just use data fetched from the server to set the state.

Let's say, data is a state property. you could pass a callback to the loadDataFromServer and loadDataFromServer calls this callback once data is fetched on it's onsuccess.

this.loadDataFromServer(searchText, function(data) {
  this.setState({data: data}};
});

This way, the component will rerender and show the results, once the data is updated.

Upvotes: 2

Related Questions