score:0

let _isMounted = false;

const HooksFunction = props => {


  const [data, setData] = useState({}); // data supposed to be object

  const fetchData = async ()=> {
    const res = await myApiClient.get('/myEndpoint');
    if(_isMounted) setData(res.data); // res.data supposed to return an object
  }

  useEffect(()=> {

    _isMounted = true;

    return ()=> {
        _isMounted = false;
    }

  },[]);

  return (
    <div>
      {/*....*/}
    <div/>
  );

}

score:1

const FetchData = () => {
  try {
    return myApiClient.get("/myEndpoint");
  } catch (err) {
    console.log("error in FetchData");
    return err.response;
  }
};

const myComponent = (props) => {
  useEffect(() => {
    const subscription = defer(FetchData()).subscribe({
      next: ({
        data
      }) => {
        setState({
          data: data
        });
      },
      error: () => {
        // error handling
      },
      complete: () => {
        // cancel loading state etc
      }
    });

    return () => subscription.unsubscribe();
  }, []);
}

Related Query

More Query from same tag