2 ways to work with promises in React Js

Last updated : Jul 30, 2023 12:00 AM

If you make API calls in the React Js application, you must know how to work with promises correctly. An API Promise is an object returned from an asynchronous function called an API.

Using Async/Await method

When you call an API, it takes some time to get a response back. Here, my code is executed asynchronously while waiting for a response. But the code is executed synchronously when I specify await within the async function. That's inside the async function.

Here is how to use the async/await approach.

Using Async/AwaitDescription
import { useCallback, useEffect, useState } from 'react'
interface User {
    userId: string
    id: string
    title: string
    completed: boolean
}
const App = () => {
  const [data, setData] = useState<User>()

  const asyncFunction = useCallback(async () => {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
      const json = await response.json()
      setData(json)
    } catch (e) {
      console.error(e)
    }
  }, [])

  useEffect(() => {
    asyncFunction()
  }, [asyncFunction])

  return <>
  <div>
    <h1>Response</h1>
    <div>{data?.id}</div>
    <div>{data?.userId}</div>
    <div>{data?.title}</div>
    <div>{data?.completed ? 'Complete' : 'Incomplete'}</div>
  </div>
  
}
export default App

Using .then()

The other option is to use the .then() method to handle the resolved value. I can chain multiple .then() methods to run a series of asynchronous tasks.

Using then() methodDescription
import { useCallback, useEffect, useState } from 'react'
interface User {
    userId: string
    id: string
    title: string
    completed: boolean
}

const App = () => {
  const [data, setData] = useState<User>()

  const regularFunction = useCallback(() => {
    try {
      fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(response =>
          response.json()
        )
        .then(res => {
          setData(res)
        })
    } catch (e) {
      console.error(e)
    }
  }, [])

  useEffect(() => {
    regularFunction()
  }, [regularFunction])

  return <>
  <div>
    <h1>Response</h1>
    <div>{data?.id}</div>
    <div>{data?.userId}</div>
    <div>{data?.title}</div>
    <div>{data?.completed ? 'Complete' : 'Incomplete'}</div>
  </div>
  
}
export default App
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...