Search code examples
reactjsreact-nativewordpress-gutenberg

Can't fetch data object entirely in react, most likely due to of fetch call delay


I'm trying to get Wordpress Rest API data about author.

So I'm using ComponentDidMount() with state:

constructor(props) {
    super(props);
    this.state = {
      data: {},
    };
}
componentDidMount() {
    apiFetch( { path: '/wp/v2/users/1' } )
      .then(data => this.setState({ data }));
}

in my render:

const { data } = this.state;

my data will be similar to this:

{
    id: "2",
    name: "Alex",
    image_url: {
        24: "http//...",
        48: "http//...",
        96: "http//..."
    }
}

So in my return if I do this:

<div className={className}>
    {data.name}
</div>

it is working and I will get "Alexander", but if add image url:

<div className={className}>
    {data.name}
    <img src={data.image_url['24']} />
</div>

I will get an error Cannot read property '24' of undefined. As I understand there is some delay for fetching and that's why I get an error.

How can I add expectation of handling? Sorry but in React I'm a beginner.

P.S. This is actually Gutenberg editor which is actually react, but has some core like apiFetch function, it is similar to fetch.


Solution

  • As you said the reactive variable won't come until the response is resolved you just have to check if it exists like that

    <div className={className}>
        {data.name}
        { data.image_url ? (<img src={data.image_url['24']} />) : (<></>) }
    </div>