Home > Net >  What's the best practice of calling API data from a function outside useEffect?
What's the best practice of calling API data from a function outside useEffect?

Time:09-24

While working with react useEffect hook, most of the example I came across in case of calling api data in useEffect hook for initiate the component is, calling api directly inside useEffce hook. For instance,

useEffect(() => {
 async function(){
  const res = await axios.get(`https://jsonplaceholder.typicode.com/${query}`);
  setData(res.data)
 }
}, []);

But what about fetch data outside the hook with a method ? For instance,

const getData = () => {
  async function(){
  const res = await axios.get(`https://jsonplaceholder.typicode.com/${query}`);
  setData(res.data)
}

useEffect(() => {
 getData();     // here eslint shows an warning "Promise returned from setData is ignored"
}, [])

is there any specific reason for avoiding second example. If not what's the proper way to call api call function in useEffect hook with proper cleanup ?

CodePudding user response:

In React component file

useEffect(() => {
 loadData(query).then(setData)
}, [query])

crate another service file to serve data from API

in service file

export const loadData = async query => {

  const res = axios.get(`https://jsonplaceholder.typicode.com/${query}`);

  return res.data;

  // You can put this API call in try catch to handle API errors
};

CodePudding user response:

Creating a separate function for calling an api is a perfect example of loading data in useEffect. You can give it parameters if you would have a paginated endpoint and call it multiple times or add polling to the page to load the data by interval. I can only see benefits by creating a function for this.

  • Related