D
D
Durin Qurkingo2019-08-04 21:45:26
React
Durin Qurkingo, 2019-08-04 21:45:26

What's the best way to handle error ,loading and respond from the server?

what is the best way to handle error ,loading and respond from the server.
I do it this way.

const [resp, setRes] = useState();
const [err, setErr] = useState("");

useEffect(() => {
  (async () => {
    try {
      const Res = await fetch(...);
      const Num = await res.json();
      if(Num){throw new Error();} //проверка
      setRes(Num);
    } catch () {
      setErr("error");
    }
  })();
}, []);

if (err !== "") {
  return <div>{err}</div>;;
} else if (Num === undefined ) {
  return <div>{'...загрузка'}</div>;
}
return (
  <div>
      <You resp={resp} />
  </div>
);

I'm not sure if my way is better. There are some flaws in my code that I didn't see. Can you show better ways to handle

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-08-04
@Sagund

The logic can be put into your own hook. Something like this:

const useFetch = (url, options) => {

  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  const fetchData = async () => {
    try {
      setIsLoading(true);
      const res = await fetch(url, options);
      const json = await res.json();
      setData(json);
      setIsLoading(false);
    } catch (error) {
      setError(error);
      setIsLoading(false);
    }
  };  

  useEffect(() => {
    fetchData();
  });

  return [
    data,
    isLoading,
    error,
    fetchData,
  ];
};

const Example = ({ slug }) => {
  const [ product, isLoading, error, fetchFn ] = useFetch(`/api/product/${slug}`);
  
  if (isLoading) return <Preloader />;

  if (error) return <Error error={error} tryAgainFn={fetchFn} />;

  if (!product) return <NotFound />;
  
  return <Product product={product} />
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question