I created this fetch
function in my React app:
const getStatus = () => {
const fetchData = async () => {
const response = await fetch(`http://localhost:3000`);
const result = response.status;
console.log(result);
return result;
};
return fetchData();
};
I want then use this function like:
getStatus() === 200 ? 'Do something' : 'Don't do something'
But now when I call function getStatus()
it returns undefined
?
How do I directly return something from getStatus()
function, which I can use for e.g. a ternary operator?
CodePudding user response:
With proper handling of Promises, it should be easier. Combine Promise handling with state to store response in.
Here's the sample code for the question.
Addition to this can also be managed for loading, so when status
is null you can keep it as loading and the rest as you want to.
import React from "react";
const AppStatus = () => {
const [status, setStatus] = useState(null);
const fetchStatus = async () => {
const response = await fetch(`http://localhost:3000`);
return response.status;
};
useEffect(async () => {
const response = await fetchStatus();
setStatus(response);
}, []);
return <div>{status === 200 ? "Do something" : "Don't do something"}</div>;
};
export default AppStatus;
CodePudding user response:
the function "fetchData" is an async function, if you want to get value with async function, you have to use "await", eg: const status = await fetchData()
.
so in you case, maybe modify it like below:
// because inner getStatus you will execute 'fetchData' function
// 'fetchData' should await it, so you have to change "getStatus" with async function
const getStatus = async () => {
const fetchData = async () => {
const response = await fetch(`http://localhost:3000`);
const result = response.status;
console.log(result);
return result;
};
const status = await fetchData();
return status
};