1

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

3
  • Are the Routes in a Switch? Commented Jan 29, 2021 at 18:28
  • yes.....it is.. Commented Jan 29, 2021 at 18:28
  • 1
    If they are in a Switch and the the /books/bookshome is on top, the other shouldn't ever be hit. Could you update your code to show a bit more detail? Commented Jan 29, 2021 at 18:30

2 Answers 2

2

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} />
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.