0

I perform a fetch in my api and it returns a 201 status, but when I try to receive it in a variable the status comes all 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 { <state>: "fulfilled", <value>: 201 }'

}

  • 2
    An `async` function wraps its return value in a `Promise` by default. You doesn't have any `return` in your `Verify`, so `status` eventually resolves to `undefined`. – InSync Jul 01 '23 at 01:33

1 Answers1

1

If you want status to equal the result of Verify, you need to await it.

const status = await Verify(test);

Also, I recommend refactoring your code to use await everywhere to simplify the flow. Try something like this:

async function Verify (test) {
  const res = await fetch('/api/test', {
    method: 'POST', 
    headers: {
     'Content-Type': 'application/json',
    },
    body: JSON.stringify( { test } ),
  });
  
  if (!res.ok) {
    throw new Error('Not-ok response from server');
  }

  return res;
}
Brad
  • 159,648
  • 54
  • 349
  • 530