0

Hello I have a question about fetch call inside componentDidMount. Here's an example code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [data, setData] = useState({ hits: [] });
  useEffect(async () => {
    const result = await axios(
      'https://hn.algolia.com/api/v1/search?query=redux',
    );
    setData(result.data);
  }, []);
  return (
    <ul>
      {data.hits.map(item => (
        <li key={item.objectID}>
          <a href={item.url}>{item.title}</a>
        </li>
      ))}
    </ul>
  );
}
export default App;

Here

useEffect(()=>{},[]);

This is the same as componentDidMount.

Inside useEffect we fetch data from server and store it into data. Then data is used to render items to page as <li> elements.

My question is, does fetch call (ie. axios) get executed AFTER App component gets mounted the first time? If so, how does data get populated in time for the first rendering?

<ul>
      {data.hits.map(item => (
        <li key={item.objectID}>
          <a href={item.url}>{item.title}</a>
        </li>
      ))}
 </ul>

My understanding is, since data is populated AFTER the first mount, it won't be available for rendering?

Maybe I'm misunderstanding the difference between MOUNTING and RENDERING?

Can someone correct me because the above code obviously does work.

Thanks.

1 Answer 1

1

Well it's not populated, but the empty array still exists, so the code doesn't crash. When the component mounts and first renders, data.hits is equal to an empty array, []. So you can map over it, but the length is 0 so the map won't produce anything. If initially you defined data.hits to be an empty object, or null or something, e.g. const [data, setData] = useState({});, THEN it would crash, cos initially data.hits is equal to undefined, and you'll get an error Can't read property .map of undefined

Sign up to request clarification or add additional context in comments.

3 Comments

Just like Jayce444said useState starts with { hits: [] } that's why your app doesn't crash. If you start useState with other than { hits: [] } then all you have to do is put data.hits && data.hits.map(... and it wouldn't crash.
Does data get populated just before second render?
@logan Yes, setData(result.data); updates the state value of data, and that causes a second re-render (in both functional and class components, both state and prop changes cause a re-render))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.