Fetching usando useEffect | React
- Fetching usando useEffect | React
const App = ({ id }) => {
const [post, setPost] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
setIsLoading(true);
const controller = new AbortController();
const { signal } = controller;
fetch(`/api/posts/${id}`, { signal })
// fetch logic
.finally(() => {
setIsLoading(false);
});
return () => controller.abort();
}, [id]);
if (typeof post === 'undefined') {
return <EmptyState />;
}
};