G
G
Gabe Jonson2017-02-26 12:00:17
React
Gabe Jonson, 2017-02-26 12:00:17

React request to server?

Good afternoon, I'm trying to learn React now, and I ran into such a problem.
I send a request to the server to get an array:

const peoples = 'https://randomuser.me/api/?results=50';

componentDidMount() {
    fetch(peoples)
    .then(res => {
      if(res.status !== 200) {
        console.log(res.status);

        return;
      }
      res.json().then(function(res) {
        this.setState({data: res});
      });
    })
  }

And accordingly I stuff the result into the component:
<Header items={data} />
And this is what happens...
First comes null, and only then the array itself...
The assumption is that it (the request) simply does not have time to be accepted before the render of the component...
But how to overcome this ?
I wonder how exactly to do this with standard methods, without libraries (jQuery or axios)
setInterval or setTimeout is somehow not an option because it looks like a crutch ... Yes, and it will not work very well (I think so)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Gamega, 2017-02-26
@gabejonson

If you want to solve the problem in the forehead, then just check the data before rendering, it won’t hurt anyway, or set the initial value for data, but React is a view layer, sending requests from the view is not the best idea
Look towards the flux architecture (I myself use redux but the common name ... )
Send requests from action, change store in redusere, and the component itself will already render everything that comes
in. It doesn’t sound wild at first glance and there is a little more code, but it is much cleaner and easier to maintain

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question