Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react fetch url

import { useEffect, useState } from 'react';

export const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(res => res.json)
      .then(setData)
      .catch(setError)
      .then(() => setLoading(false))
  }, [url]);
  
  return [data, isLoading, error];
};

function Profile() {
  const [data: profile, isLoading, error] = useFetch('/profile');
  return (
    <>
      {loading && <Spinner />}
      {data && <Profile data={data} />}
      {error && <Toast error={error} />}
    </>
  );
}
 
PREVIOUS NEXT
Tagged: #react #fetch #url
ADD COMMENT
Topic
Name
3+3 =