Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React fetch stops working after page refresh

I am fetching a single object. When the page loads for the first time the fetched elements does render to the DOM. When i refresh the page the fetch does not work anymore and i get an error – Uncaught TypeError: Cannot read properties of undefined (reading 'name')

enter image description here

import { useState, useEffect } from "react";
import axios from "axios";

function DataFetching() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const loadProducts = async () => {
      const response = await axios.get("https://CENSORED/");
      setProducts(response.data);
    };
    loadProducts();
  }, []);

  return (
    <>
      <div className="App">
        <p>{products.product.name}</p>
      </div>
    </>
  );
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Thats because for first time render there is no product yet , and after fetching and rerender component it is available , so in first render you have no access to object and it throw error

you can do {products?.product?.name}

Or You can also write your code like

import { useState, useEffect } from "react";
import axios from "axios";

function DataFetching() {
  const [products, setProducts] = useState(null);

  useEffect(() => {
    const loadProducts = async () => {
      const response = await axios.get("https://CENSORED/");
      setProducts(response.data);
    };
    loadProducts();
  }, []);


if(!products) return <div>loading...</div>

  return (
    <>
      <div className="App">
        <p>{products.product.name}</p>
      </div>
    </>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading