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

Can't access object values in React

I have a functional React component that I want to return a list of information about a car. The first three lines of the return statement (model, maker, release) load with no problem, but the categories won’t load because React says ‘category’ is undefined.

When I console.log car after it is set in state, the car object has the categories key on it, and I can expand that to show three category objects. I can then expand each of those to show category.id and category.name.

So is there a way to access car.categories.category.name? Is the issue that there are three objects?

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

const CarDetails = () => {
    const {carsId} = useParams();
    const [car, setCar] = useState([])

    const loadCar = () => {
        getOneCar(carsId)
            .then(data => {
                setCar(data)})
    }

    useEffect(() => {
        loadCar()
    }, []);

    useEffect(() => {
        console.log(car)
    }, [car])


    return (
        <>
        <h2>{car.model}</h2>
        <p>Maker: {car.maker}</p>
        <p>Year released: {car.released}</p>
        {/* <p>Categories: {car.categories.category.name}</p> */}
        </>
    )

This is what the object looks like

"model": Corvette
"maker": Chevrolet
"categories": [
            {
                "id": 1,
                "category": {
                    "id": 1,
                    "name": "Sports"
                }
            },
            {
                "id": 2,
                "category": {
                    "id": 2,
                    "name": "Hybrid"
                }

>Solution :

I think car.categories is an array not an object.
So car.categories.category does not work.
Please try car.categories[0].category, car.categories[1].category, … like this.

<>
  <h2>{car.model}</h2>
  <p>Maker: {car.maker}</p>
  <p>Year released: {car.released}</p>
  {/* <p>Categories: {car.categories.category.name}</p> */}
  <p>Categories: </p>
  {car && car.categories.map(item => {
    return(<span>{item.category.name}</span>)
  })}
</>

Thanks.

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