search

Home  >  Q&A  >  body text

How to correctly obtain the status of fetch?

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 { <state>: "fulfilled", <value>: 201 }'

}

P粉124070451P粉124070451441 days ago569

reply all(1)I'll reply

  • P粉509383150

    P粉5093831502023-09-09 09:45:31

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

    const status = await Verify(test);

    Additionally, I recommend refactoring your code to use await everywhere to simplify the process. 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;
    }

    reply
    0
  • Cancelreply