Reputation: 9644
(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
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));
After about a second, new data is received from the server and the result is refreshed again.
Obviously what I want to do is
What is the proper way of achieving this?
Upvotes: 6
Views: 953
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
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