Good morning everyone!
I am currently working on the adopt a pet project in the React Lesson and I am having a bit of a hard time understanding the directions of question 13 which states:
To make this page render the details for the actual pet your user has selected, use the useParams()
hook to get the value of the :id
URL parameter in the PetDetailsPage
component.
To test that your code works, refresh the page. You should see the details for the pet whose picture you clicked previously.
(https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-22-react-part-ii/modules/wdcp-22-react-router/projects/pet-adoption-website)
I am properly using the useParams hook ( so I thought), but I am not sure I am questioning if that is the right hook to use? Even though the directions say to use useParams why couldn’t I use useRouteMatch hook If I am trying to receive a URL? Basically I am asking “what am I doing wrong here?” because I cannot get the proper results I am looking for in the project. I have looked through the lesson, forms and videos but no obvious answer.
detail/index. js
import React, { useEffect, useState } from 'react';
import { getPetDetails } from '../../api/petfinder';
import Hero from '../../components/hero';
import {useParams} from 'react-router-dom';
const PetDetailsPage = () => {
const [data, setData] = useState();
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const {id} = useParams() // <--- Update me!
useEffect(() => {
async function getPetsData() {
try {
const petsData = await getPetDetails(id);
setData(petsData);
setError(false);
} catch (e) {
setError(true);
}
setLoading(false);
}
getPetsData();
}, [id]);
return (
<div>
{loading ? (
<h3>Loading...</h3>
) : error ? (
<div>
{/* Redirect to /pet-details-not-found if there was an error! */}
</div>
) : (
<main>
<Hero
image={data.photos[1]?.full || 'https://i.imgur.com/aEcJUFK.png'}
displayText={`Meet ${data.name}`}
/>
<div className="pet-detail">
<div className="pet-image-container">
<img
className="pet-image"
src={
data.photos[0]?.medium || 'https://i.imgur.com/aEcJUFK.png'
}
alt=""
/>
</div>
<div>
<h1>{data.name}</h1>
<h3>Breed: {data.breeds.primary}</h3>
<p>Color: {data.colors.primary || 'Unknown'}</p>
<p>Gender: {data.gender}</p>
<h3>Description</h3>
<p>{data.description}</p>
</div>
</div>
</main>
)}
</div>
);
};
export default PetDetailsPage;
App.js
import HomePage from './pages/home';
import SearchPage from './pages/search';
import PetDetailsPage from './pages/detail';
import PetDetailsNotFound from './pages/petDetailsNotFound';
import Navigation from './components/navigation';
import {BrowserRouter as Router, Route} from 'react-router-dom';
function App() {
return (
<div>
<Router>
<Route path = '/:type/:id'>
<PetDetailsPage />
</Route>
<Navigation />
<Route path="/:type?">
<HomePage />
</Route>
</Router>
</div>
);
}
export default App;