score:1

Accepted answer
  • you cannot await on a setstate (seturl) function.
  • you return in your fetch data which is not used later.

you need to first change your mindset on how you think in react hooks and when you need to use them.

as far as i understand you want to fetch some data from server, update the store on successful retrieval, and show an error when the request fails.

you should do this all the way or don't do this at all. you can put the dispatch in the hook or you can forget about the hook and write a reusable fetchdata function and handle sethaserror in your component's useeffect.

there are many ways to solve this but this is my preferred solution:

import react, { fragment, usestate, useeffect, usereducer } from 'react';
import axios from 'axios';

export const usehttprequest = (url, updatestore) => {
  const [haserror, sethaserror] = usestate(false);

  const fetchdata = async (url) => {
    sethaserror(false);
    try {
      const res = await axios(url);
      const responsedata = res.data.data.data;
      updatestore(responsedata);
    } catch (error) {
      sethaserror(true);
    }
  };

  useeffect(() => {
    if (url) {
      fetchdata(url);
    }
  }, [url]);

  return { fetchdata, haserror };
};
// in case you want to fetch the data on component render
const { fetchdata, haserror } = usehttprequest(url, (data) => dispatch({
  type: set_categorydata,
  payload: data
}));

// in case you want to fetch it in a callback
const clickbutton = () => {
  fetchdata(somecustomurl);
}

finally, you can generalize your dispatchers so you don't need to send the whole function to the hook and only send the dispatcher name.


Related Query

More Query from same tag