Iago Barreto
Iago Barreto

Reputation: 113

How to resolve "Can't perform a React state update on an unmounted component. "

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

Upvotes: 0

Views: 375

Answers (2)

Fahad Shinwari
Fahad Shinwari

Reputation: 968

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();
 }, []);

Upvotes: 1

Wen W
Wen W

Reputation: 2647

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..

Upvotes: 1

Related Questions