Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs - getting data from server and updating

(reactjs newbie here)...

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

  • a simple search box
  • user types in a search text
  • data is fetched from the server and is displayed

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?

like image 425
ericbae Avatar asked Jun 06 '14 07:06

ericbae


People also ask

How fetch data from server in React?

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.

Which method is used to update the data to the React app?

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() .

How do you immediately update in React?

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.


1 Answers

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.

like image 164
viven Avatar answered Oct 03 '22 22:10

viven