Home > database >  Is it an incorrect practice to use URL params as a way to fetch data using react router in an react
Is it an incorrect practice to use URL params as a way to fetch data using react router in an react

Time:04-14

In my app I have a Home page that has a child named Posts the routes are set up in the following manner:

<Route path='/' element={<Home />}>
  <Route path='/posts/popular' element={<Posts />} />
  <Route path='/posts/new' element={<Posts />} />
</Route>

I would like to set it up where if I am on the popular path then my api call will be:

axios.get('/posts?sort=-popular')

But if I am on new, then the call would be:

axios.get('/posts?sort=-createdAt')

The way I was thinking of implementing it was to make the second param into a selector like:

<Route path='/' element={<Home />}>
  <Route path='/posts/:sortBy' element={<Posts />} />
</Route>

// in my Posts component I would call useParams
const {sortBy} = useParams();

// then in useEffect
axios.get(`/posts?sort=-${sortBy})

But this feels off, like I am doing it wrong. What is a better way, if any, of implementing this functionality?

CodePudding user response:

What you did is ok, but it will make the component harder to reuse, also if you changed the path you will need to change also the component Posts. It’s better to add a new prop sortBy inside your component Posts and pass the prop inside your Route component.

<Route path='/' element={<Home />}>
 <Route path='/posts/popular' element={<Posts sortBy="popular" />} />
 <Route path='/posts/new' element={<Posts sortBy="new"/>} />
</Route>

CodePudding user response:

You can pass props into the <Posts /> component in your Route.

Here's an example:

<Route path='/' element={<Home />}>
  <Route path='/posts/popular' element={<Posts sort="popular" />} />
  <Route path='/posts/new' element={<Posts sort="createdAt" />} />
</Route>

Then inside Posts you can use the prop to determine which call to make:

const Props = ({ sort }) => {

// then in useEffect
axios.get(`/posts?sort=-${sort})
  • Related