I’m trying to reload the API data whenever I click a navbar link.
I know the approach should be like to reload a state but I’m lost in the way to achieve it..
I’m using <Link />
of react-router v6+ to achieve this goal.
- App.js
<Router>
<Routes>
<Route path="/" element={<MainPage />} />
</Routes>
</Router>
- Navbar.js
export default function Navbar() {
return (
<>
<ul>
<li>
<Link to="#link">link</Link>
</li>
</ul>
</>
}
- Data.js
const [data, setData] = useState([])// I'm trying to get how this data get empty every time (each and every sec or min) clicking to a navlink
//so that it gets reloaded and fetch new data
useEffect(() => {
axios.get('BASE-URL').then(() => setData(data.slice(0, 1))) //I've sliced the data to get only 1 items (total items fetched: 100 items in a array)
}, [])
//...
I don’t know what I do to get the issue solved.
Any help would be great!
Thank you.
2
Answers
extract that API call in the function, call that function inside a useEffect and add onClick event listener on that link that triggers the same function
Reloading API Data on Navbar Link Click in React with React Router v6+
To reload API data whenever a navbar link is clicked using React Router v6+, you can follow these steps:
Now, clicking the navbar link will trigger the reload of data from the API, updating the state with fresh data. Adjust the code according to your project structure and requirements.