skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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:

    1. Create a Data Fetching Function:
      
      export const fetchData = async () => {
        try {
          const response = await axios.get('BASE-URL');
          return response.data.slice(0, 3);
        } catch (error) {
          console.error('Error fetching data:', error);
          return [];
        }
      };
      

    1. Manage Data Using State:
      
      const [data, setData] = useState([]);
      
      useEffect(() => {
        fetchData().then((newData) => setData(newData));
      }, []);
      

    1. Reload Data on Navbar Link Click:
      
      import { fetchData } from './Data';
      
      export default function Navbar() {
        const handleLinkClick = async () => {
          const newData = await fetchData();
          setData(newData);
        };
      
        return (
          <>
            <ul>
              <li>
                <Link to="#link" onClick={handleLinkClick}>
                  link
                </Link>
              </li>
            </ul>
          </>
        );
      }
      

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search