N Pavlov
N Pavlov

Reputation: 23

React-router links don't work when accessed directly

I've got a simple React app with react-router that fetches data (say, a list of countries) in its App component which is then mapped to links.

The routing logic is in the App component. There are two routes: the base link ('/', shows a base page) and the '/:id' link (shows pages based on data fetched with useEffect and then mapped to components). Everything works fine when following links through the app (i.e. '/' -> '/Mexico'. But when I try to access parametrized link directly, the data seems to be not set at all.

I believe the problem is in the useEffect, for some reason it doesn't seem to fetch data unless starting from the '/'. I might be wrong, but for now I am stuck. Any help would be greatly appreciated.

Sample code:

const App = () => {
  const url = 'http://localhost:3001/data'
  const [data, setData] = useState([])

  useEffect(() => {
    console.log('useeffect in use');
    (async () => {
      const res = await axios.get(url)
      setData(res.data)
    })()
  }, [])

  const match = useRouteMatch('/:id')
  const country = match 
    ? data.find(x => x.country === match.params.id)
    : null

  return(
    <div className='container'>
      <Search data={data} />
      <Switch>
        <Route path='/:id'>
          <Country country={country} />
        </Route>
        <Route path='/'>
          <div>Base</div>
        </Route>
      </Switch>
    </div>
  )
}

Upvotes: 0

Views: 518

Answers (2)

N Pavlov
N Pavlov

Reputation: 23

Okay, now that I've got it solved it seems too easy. But I've just inserted the following block of code into the App component:

if (data.length < 1) {
  return(
    <div>Loading data...</div>
  )
}

Thanks all for your input!

Upvotes: 0

qve1t
qve1t

Reputation: 137

There is a problem with this piece of code:

const country = match 
  ? data.find(x => x.country === match.params.id)
  : null

When you enter your main path '/' you make a call to the api in useEffect. Next, you get an answer and call setData. You have some data in the array and you can succesffully call a data.find method. But when you enter to the parametrized link directly, data.find will return undefined, because your data is an empty array. Make sure that you will fetch data before matching the url parameter.

Upvotes: 1

Related Questions