alin11g
alin11g

Reputation: 35

Can´t display data in React

I cant figure out why I cant display the data of producto, when I write the code and save the file the data loads, but when I try refreshing the browser I get this error:

TypeError: Cannot read properties of undefined (reading 'id')

import React, { useState, useEffect } from "react";
import ProductoService from "../../../api/producto.service";
import { useParams } from "react-router-dom";

const VerProducto = () => {
const {id} = useParams();
const [producto, setProducto] = useState([]);
const [loading, setLoading] = useState(false);

useEffect(() => {
    
    const getProducto = async () => {
        setLoading(true);
        const res = await ProductoService.get(id);
        setProducto(res.data);
        setLoading(false);
    }
    getProducto();
}, [id]);

const Loading = () => {
    return(
        <>
            cargando...
        </>
    )
}

const MostrarProducto = () => {
    return(
        <>
            <h1>{producto.data.id}</h1>
        </>
    )
}

    return (
        <div className="contenido">
            {loading? <Loading/> : <MostrarProducto/>}
        </div>
    );


}

export default VerProducto;

Upvotes: 0

Views: 81

Answers (1)

WebbH
WebbH

Reputation: 2422

producto is an empty array on initial render. Change it to be undefined

const [producto, setProducto] = useState();

and then just check whether it is defined in `MonstrarProducto':

const MostrarProducto = () => {
  return(
    <>
      {producto && <h1>{producto.data.id}</h1>}
    </>
  )
}

Upvotes: 1

Related Questions