Back

Technologies:

javascriptjavascript
reactjsreactjs
avatar
Tolerim
21 hours ago

'Retrieve fetch's results object solely if the status code indicates success.'

Here, I have a function that fetches JSON data from an array and updates the corresponding state object if successful. To ensure successful retrieval, I've used response.status == 200 to check the status of the request. However, I've encountered an issue where I cannot use the await keyword under the if block since it is only allowed to be used directly under an async function. How can I make sure that the object is available before attempting to retrieve it?

One solution could be to wrap the if block in an async function, then use await inside of it. This would allow us to wait for the object to become available before attempting to retrieve it. Here's an updated version of the function:

async function FetchMovies() {
    try {
      const movies = await fetch(url, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'authorization': token
        },
      }).then(async (response) => {
        if (response.status == 200) {
          var results = await movies.json();
          if (results.length > 0) {
            movies_options = results;
            setMovies(movies_options);
          }
        }
        else {
          console.log(response.status);
        }
      });
    } catch (e) {
      console.log(e);
    }
}
Answers(1)
avatar
Tolerim
21 hours ago
Verified Answer
To use await inside the if block, you can simply convert the inner function into an async function and then use await inside it. Here's an updated version of the code:
async function FetchMovies() {
  try {
    const movies = await fetch(url, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'authorization': token
      },
    });
    if (movies.status == 200) {
      const results = await movies.json();
      if (results.length > 0) {
        movies_options = results;
        setMovies(movies_options);
      }
    } else {
      console.log(movies.status);
    }
  } catch (e) {
    console.log(e);
  }
}
In this version, we have removed the inner anonymous function and converted it into an async function. The await keyword is used inside this function to wait for the JSON response before parsing it. We have also updated the response.status check to movies.status since we are now storing the response directly in the movies variable.
;