Danny
Danny

Reputation: 327

Problem with routing in react with params

hey guys I am learning react as I'm trying to build a website, I am facing problem with the routing using params and without. I have these routes in index.js,

This is book's home

<Route exact path="/books/bookshome" component={BookList} />

and another route to fetch individual books

<Route exact path="/books/:slug" component={SingleBook} />

The problem is whenever I open the BookList, an api request will be send by the SingleBook component and that returns an error. How can I avoid that?

I tried checking a condition in useEffect in SingleBook but it doesn't seem to work.

if(slug !=="bookshome") { fetch }

Is there a way to solve this issue or should I change the url ?

Thanks

Upvotes: 1

Views: 194

Answers (2)

Pavan
Pavan

Reputation: 858

Best practices to use /books is for BookList component and /books/:id or /books/:name which should resolve your problem too.

If you want keep urls as is then try putting BookList route above the Single Book route with exact param only for BookList route

I suggest to change the URLs and follow best practices.

Upvotes: 1

Rahul
Rahul

Reputation: 402

Keep the BookList route above the SingleBook route and remove exact from slug route:

<Route exact path="/books/bookshome" component={BookList} />
<Route path="/books/:slug" component={SingleBook} />

Upvotes: 2

Related Questions