简体   繁体   中英

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')

在此处输入图像描述

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM