I am trying to display a specific beer based on the beer id I am appending to the url
import React from "react";
import { useState, useEffect } from "react";
import axios from "axios";
import {
Routes,
Route,
Link,
useNavigate,
useLocation,
} from "react-router-dom";
export default function SingleBeer() {
const [beers, setBeers] = useState([]);
useEffect(() => {
axios
.get(`https://ih-beers-api2.herokuapp.com/beers`)
.then((response) => setBeers(response.data));
}, []);
const location = useLocation();
let beerId = location.pathname.split("/").pop();
const navigate = useNavigate();
let singleBeer = beers.filter((beer) => beer._id === beerId);
console.log(singleBeer)
return (
<div>
<h1>Single Beer</h1>
<h5 onClick={() => navigate("/beers")}> Go Back</h5>
<h1>{singleBeer[0].name}</h1>
</div>
);
}
When I click show Details button for the corresponding beer on my Beers.js component the SingleBeer component doesn't render, instead I get the error "Why am I getting Uncaught TypeError: Cannot read properties of undefined (reading 'name')"
If I remove the 'h1' with the singleBeer[0].name, I can see the console.log for the single beer im not sure why the 'name' property of the single beer object is coming back as undefined if the object shows up in the console, all I am trying to do is access the specific beer route when I click show details in the previous component
{singleBeer[0].name}
from my component, I see the single object from my filter method log to the console, when I dont remove it , the component doesnt render at all. – mattangel Aug 12 '22 at 22:57