I'm doing a fetch in my api and it returns a 201 status, but when I try to receive it in a variable, the status becomes weird.
useEffect(() => { async function Verify (test) { await fetch("/api/test", { method: "POST", headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({test: test}), }).then((response) => { res = response.status; console.log(res); //thats print '201' return res; }); } const status = Verify(test); console.log(status); //thats print 'Promise {: "fulfilled", : 201 }' }
If you want
status
to be equal to the result ofVerify
, you need toawait
it.Additionally, I recommend refactoring your code to use
await
everywhere to simplify the process. Try something like this: