Home > Blockchain >  React fetch stops working after page refresh
React fetch stops working after page refresh

Time:07-14

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>
    </>
  );
}

CodePudding user response:

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>
    </>
  );
}

CodePudding user response:

It's because the 'products' state have no children yet, so the 'name' is undefined.

A simple solution is to check if the 'products' state have 'product' child inside before rendering.

Like this :

<p>{products.product ? products.product.name : ''}</p>
  • Related