Ali Zeynalov
Ali Zeynalov

Reputation: 3017

react-native - call another function when fetch is over

I'm new to React-Native

I have fetch, through which I get some data. What I want to do is to call another function or update the state, after the request is over and data is ready. Here is my code.

getProducts()
    {
        return fetch(prodUrl, {method: "GET"})
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({brandList: responseData.products});
                console.log("Brands State -> : ",this.state.brandList)
            })
            .done();
    }

I call this getProducts() function in componentWillMount() and trying to use fetched data in render(). After I set the state, I can't see the change when I try to console.log(), most probably because fetch() is async. How can I stop execution of render() function before fetch() is over? Or can you recommend any other request type rather then fetch() which is sync.

Upvotes: 0

Views: 1080

Answers (2)

Matt Aft
Matt Aft

Reputation: 8936

It's not because fetch is async, you already have your responseData at that point. It is because setState doesn't change state immediately, so you're console.log is being called before state is being changed. setState has an optional callback as it's second parameter that will be called once set is done being updated, so you can change it like this to see the effect correctly:

getProducts()
    {
        return fetch(prodUrl, {method: "GET"})
            .then((response) => response.json())
            .then((responseData) => {
                this.setState(
                  {brandList: responseData.products},
                  () => console.log("Brands State -> : ",this.state.brandList)
                );  
            });
    }

Upvotes: 2

Anna Melzer
Anna Melzer

Reputation: 1613

You do not want to "stop" the render() function from being executed. You can, however, apply a check in render if the data is available and render a spinner or something else while it is not.

Very rough sketch of how this could look like:

render() {
  let component = this.state.brandList ? <ComponentWithData/> : <Spinner/>;
  return component;
}

Upvotes: 1

Related Questions