this is my code why it shows id undefined? i want in the sale component access to both title & id of each book but id is undefined.how can i show the value of id in the Sale component? thank you for your help!
App.js
<Route path="books" element={<Dashboard />} />
<Route path="books/:booktitle" element={<BookDetails />} />
<Route path="books/:booktitle/sale/:id" element={<SaleStore />} />
Dashbaord:
{books.map((book) => (
<div className="col" key={book.id}>
<div className="card h-100" >
<div className="card-img-top pb-5 mb-5">
</div>
<div className="card-body">
<Link to={`/books/${encodeURIComponent(book.title)}`}>
<button type="submit" className="btn custome-btn purple-active-ghost w-100">
{book.title}
</button>
</Link>
// rest of code
Detail
:
const { booktitle, id } = useParams();
console.log("book Title:", booktitle);
console.log("book Id:", id);
<Link to={`/books/${encodeURIComponent(booktitle)}/sale/${id}`}>
<button type="submit" className="btn custome-btn purple-active-ghost w-100">
go to sale
</button>
</Link>
Sale
:
const { booktitle, id } = useParams();
console.log("book Title:", booktitle);
console.log("book Id:",id);
<p>{booktitle}</p> //
<p>{id}</p> // undefiend
2
Answers
It looks like you have a route for Sale that includes both
:booktitle
and:id
parameters:In your
Link
component in the BookDetails component, you are correctly constructing the URL:However, when you use
useParams
in the Sale component, it seems that you might not be providing theid
parameter correctly in the URL.Make sure that when you navigate to the Sale component, you are providing both
:booktitle
and:id
in the URL. For example, if you have a book with title "example" and ID "123", the URL should look like:If the URL is correct, the
useParams
in the Sale component should correctly extract bothbooktitle
andid
. If it’s still showingundefined
, double-check the URL and make sure you are providing the parameters correctly. Additionally, you may want to log the entireparams
object to see what is being extracted:This way, you can inspect the entire
params
object and see if the parameters are being correctly parsed from the URL.It would appear that the
BookDetails
component has the undefinedid
param and passes it through to the link used to navigate to the sales page.I’d suggest a routing pattern where the book id is used earlier in the route path.
Exmaple:
Update the dashboard to link to a detail page with title and id.
Now both
title
andid
will be defined int he details component. Link to the sales page.Now the book
title
andid
should also be available in the sale component.