Answer the question
In order to leave comments, you need to log in
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>
);
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question