I'm trying to improve the UI of my React app, and one thing I want to try and work out is how to pre fire an API call when a user hovers over a link, so by the time they're clicked through, the data has already been loaded and FakeAPI.jsx
has already populated the state with the data from the API call
Currently I've got the below:
//Home.jsx
import {Link} from 'react-router-dom';
const Home = () => {
return (
<div className="links">
//I would want to load the API call when a user hovers on the below link
<Link to="/fakeApi">Fake Api</Link>
</div>
);
};
export default Home;
And then the API call
//FakeApi.jsx
import React, { useState, useEffect } from 'react';
const FakeApi = () => {
const [data, setData] = useState([])
useEffect(()=>{
setTimeout(() => {
//simulates an api call to the backend
setData(['1','2','3'])
}, 250);
}, [])
return (
<div>
Fake Api call
{data.map(entry=>(
<div key={entry}>number is {entry}</div>
))}
</div>
);
};
export default FakeApi;
The only solution i've come up with so far is to put the api call in home.jsx
, and then call it on hover and pass the data through as props,
as per below:
//Home.jsx
import React from 'react';
import {Link} from 'react-router-dom';
import LinkWithPreload from '../shared/LinkWithPreload';
const Home = () => {
const [data, setData] = useState([])
useEffect(()=>{
setTimeout(() => {
//simulates an api call to the backend
setData(['1','2','3'])
}, 1000);
}, [])
return (
<div className="links">
<Link to="/fakeApi" props={data}>Fake Api</Link>
</div>
);
};
export default Home;
however in reality home.jsx
is a very big file with several other functions and API calls, and I'm trying to keep it tidy so I'm looking for another solution - to keep each call to a route,
Thanks for your help!