Sometimes, we want to get promise value in React and JavaScript.
In this article, we’ll look at how to get promise value in React and JavaScript.
How to get promise value in React and JavaScript?
To get promise value in React and JavaScript, we can use await
.
For instance, we write:
import React from "react";
export default function App() {
const [ans, setAns] = React.useState();
const getAnswer = async () => {
const res = await fetch("https://yesno.wtf/api");
const data = await res.json();
setAns(data);
};
React.useEffect(() => {
getAnswer();
}, []);
return <>{JSON.stringify(ans)}</>;
}
to create the getAnswer
function that calls fetch
with await
to get the response data from the promise returned by fetch
.
Likewise, we do the same with the json
method.
And then we call setAns
to set the value of ans
.
Next, we call getAnswer
in the useEffect
callback to call when the component mounts.
And finally, we render ans
in the return
statement.
Conclusion
To get promise value in React and JavaScript, we can use await
.