0

The full Error message is about this:

And here is the code I wrote using axios to consume the ny times API.

export default function App() {
  const [info, setInfo] = useState([]);

  // Load dos dados da api
  useEffect(() => {
    async function loadNews() {
      const response = await api.get('/arts.json');

      const { results } = response.data;

      console.log(results);
      setInfo(results);
    }

    loadNews();
  }, []);

  return (
    <>
      <Main>
        <Title>Technology</Title>
        <Content>
          {info.map(news => <Text key={news.url}>{news.title}</Text> )}
        </Content>
        <Title>Science</Title>
      </Main>
    </>
  );
}

Is a better way of loading these json object. including maybe a pagination? Why is it giving me this error? should i use async functions outside useEffect hook but I dont know how

Iago Barreto
  • 103
  • 1
  • 11
  • Does this answer your question? [Can't perform a React state update on an unmounted component](https://stackoverflow.com/questions/53949393/cant-perform-a-react-state-update-on-an-unmounted-component) – Ajeet Shah Oct 05 '20 at 01:41

2 Answers2

1

nice little trick as mentioned in the link @Ajeet posted:

export default function App() {
  let isMount = false;
  const [info, setInfo] = useState([]);

  // Load dos dados da api
  useEffect(() => {
    isMount = true;
    async function loadNews() {
      const response = await api.get('/arts.json');

      const { results } = response.data;

      console.log(results);
      setInfo(results);
    }

    if (isMount) loadNews();
  return ()=>{isMount = false};
  }, []);

  return (
    <>
      <Main>
        <Title>Technology</Title>
        <Content>
          {info.map(news => <Text key={news.url}>{news.title}</Text> )}
        </Content>
        <Title>Science</Title>
      </Main>
    </>
  );
}

Looking at the code, if you do a console.log after loadNews(); you will probably see multiple renders. Having the isMount there will prevent setting the info multiple times..

Wen W
  • 2,434
  • 1
  • 10
  • 15
1

You can also use a try and catch block on your asynchronous functionction

useEffect(() => {
const loadNews = async () => {
    try {
        const response = await axios.get('arts.json');
        const { results } = response.data;
       console.log(results);
       setInfo(results);
      } catch (err) {
        // Handle Error Here
        console.error(err);
     }
     };

    loadNews();
 }, []);
Fahad Shinwari
  • 968
  • 7
  • 7