I have a function which needs to submit an API request, wait for the response and return whether the status of the response was within the 200-299 range (i.e., the response.isOk attribute).
However, when I call the function from a component, I assume I get the response too late (the function doesn't wait for the fetch to finish and instead returns undefined). Is there a way around this?
AuthFunctions.js
export function validateToken(token) {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
};
return fetch("/api/validateToken", requestOptions).then(
(response) => response.ok
);
}
App.js
function App() {
return (
<BrowserRouter>
<div className="App">
{!token ||
(token === "" && token === undefined) ||
!validateToken(token) ? (
<AuthPage setToken={setToken} />
) : (
<>
<Routes>
<Route
exact
path="/dashboard"
element={<Dashboard token={token} />}
></Route>
</Routes>
</>
)}
</div>
</BrowserRouter>
);
}
useEffecthook to make the call and store the result in a state by using theuseStatehook. Make your component render a loading indicator of some kind until the result exists in the state.