Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Created February 5, 2023 15:21
Show Gist options
  • Save MirzaLeka/67e74a62ffa733b93614f0c2d45e41c4 to your computer and use it in GitHub Desktop.
Save MirzaLeka/67e74a62ffa733b93614f0c2d45e41c4 to your computer and use it in GitHub Desktop.
React Hooks Async Await

React Hooks with Async Await

Learn how to use Async Await with common React Hooks

UseEffect

State

const [ APIData, setAPIData ] = useState<APIInterface>();

Effect

  useEffect(() => {
    const fetchAPIData = async () => {
      const data = await getAPIData('none, one or more params')
      setAPIData(data)
    }

    fetchAPIData()
    // you may need to disable eslint rule for empty brackets
  }, [])

API Call

const getAPIData = async (param: string) {
  const response = await fetch(`/api/${param}`)
  const data = await response.json();
  return data;
}

UseCallback

State

const [ APIData, setAPIData ] = useState<APIInterface>();

Hook + API Call

const getAPIData = useCallback(async (param: string) => {
  const response = await fetch(`/api/${param}`)
  const data = response.json();
  setAPIData(data);
}, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment