1

I am making a fetch request that returns an array of strings.

fetch(linkFetch)
            .then(resp => resp.json())
            .then(arr => {
                that.setState({
                    images: arr
                });
            })
            .then(this.test());

on the last line you can see I try to call the method test() which is just trying to access the state that was set in the fetch() request.

test(){
    console.log(this.state.images[1]);
}

console logs 'undefined'

However, if I assign test() to a button or something so that I can manually call it works fine which leads me to believe that when I call .then(this.test()); in the fetch request it is actually being called before the state is set.

How can I make sure it gets called after the state has been set in the fetch request?

gabrriel_bu
  • 67
  • 2
  • 10

2 Answers2

4

The argument you pass to then needs to be a function.

You are calling this.test immediately (i.e. before the asynchronous function has resolved) and passing its return value (undefined as there is no return statement).

You already have an example of how to do this correctly on the previous line of your code.

fetch(linkFetch)
    .then(resp => resp.json())
    .then(arr => {
        that.setState({
            images: arr
        });
    })
    .then(() => {
        this.test();
    });
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    @The_Lone_Devil — No, because that disconnects the function from the `this` context (and we can see that the test method uses `this`). – Quentin Mar 22 '18 at 14:00
  • You might want to add that to the answer as it looks like my comment is what they thought they were doing. :) – Justinw Mar 22 '18 at 14:02
0

React provides a way to call a function after the setState has been executed. You can use the callback function as described in the react documentation https://reactjs.org/docs/react-component.html#setstate

You can pass your desired function as a second argument to the setState call.

that.setState({ key:Val}, that.test);

Arjun Nair
  • 111
  • 4
  • @Quentin setState is an asynchronous call and hence the then block may get executed before React updates the state. I believe using the callback would ensure that the function is called only after setState – Arjun Nair Mar 23 '18 at 08:40