Home > front end >  React show data from array of objects
React show data from array of objects

Time:09-29

Today I made a useFetch hook to get all the data from a certain category. As you can see on the image it's possible to see all the data in JSON format. Also you can see that it is in an array of objects. I was wondering how I can show this data in normal format like on the page. Most of the time I'm getting the error of data.name NULL. But as you can see the data is fetched correctly in JSON format on the image. I just don't understand how to show all this data normally. Any suggestions?

enter image description here

enter image description here

import React from "react";
import "../Style/menu.css";
import { useParams, withRouter } from "react-router-dom";
import useFetch from "../ApiService/useFetch";
import { render } from "@testing-library/react";

const Product = () => {

    const { id } = useParams();
    const { data, error, isPending } = useFetch("http://localhost:8080/products/category/"   id);

        return (
            <p>{JSON.stringify(data)}</p>
        )
}

export default Product;
import { useState, useEffect } from "react";

const useFetch = (url) => {
    const [data, setData] = useState(null);
    const [isLoading, setIsPending] = useState(true);
    const [error, setError ] = useState(null);


useEffect(() => {
        fetch(url) //custom url so you can reuse it
        .then(res => {
            if(!res.ok) {
                throw Error('could not fetch data');
            }
            return res.json();
        })
        .then(data =>  {
            setData(data);
            setIsPending(false)
            setError(null)
        })
        .catch(err => {
            setError(null)
            setIsPending(false)
        })
    }, [url]);

    return {data, isLoading, error} //use properties with custom hook
}

export default useFetch;

CodePudding user response:

This might be helpful for you

...

const Product = () => {

    const { id } = useParams();
    const { data, error, isPending } = useFetch("http://localhost:8080/products/category/"   id);

        return (
            { data && data.length &&
                data.map((row) =>{
                  <p>row.name</p>
                })
            }
        )
}

...

CodePudding user response:

your useFetch is async, as I can see isPending variable, why don't you use this ?

const { id } = useParams();
const { data, error, isPending } = useFetch("http://localhost:8080/products/category/"   id);


    return (
        <p>{isPending ? null : JSON.stringify(data)}</p>
    )
  • Related