(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?
The most accessible way to fetch data with React is using the Fetch API. The Fetch API is a tool that's built into most modern browsers on the window object ( window. fetch ) and enables us to make HTTP requests very easily using JavaScript promises.
forceUpdate() By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate() .
To update state in React components, we'll use either the this. setState function or the updater function returned by the React. useState() Hook in class and function components, respectively.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With