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.
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
Here is how to use the
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
The other option is to use the
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