Search code examples
javascriptreactjsreact-nativeasyncstorage

return undefined fetch inside AsyncStorage


I have a react-native app where I do a call to an api where it should return the JSON but I'm just having undefined.

export function fetchFromAPI() {
  AsyncStorage.getItem('@token', (errToken, token) => {
    let token = null;

    const requestBody = { token: token };

    return fetch(url, {
      method: 'POST',
      body: JSON.stringify(requestBody)
    })
    .then((response) => response.json())
    .then((responseJSON) => {
      console.log(responseJSON); // <-- this shows the correct JSON data
      return responseJSON;
    }).catch((error) => {
      // console.error(error);
    });
  });
}

I also call that funcion like this:

const apiData = fetchFromAPI();

If I do console.log() inside the fetch function, it returns the JSON data but if I do to apiData, it just gets undefined.

Does anyone has some idea why its like this, I'm doing something wrong?


Solution

  • You can use Promise to get response from fetchFromAPI function, like

    export function fetchFromAPI() {
      return new Promise((resolve, reject) => {
        AsyncStorage.getItem('@token', (errToken, token) => {
          let token = null;
    
          const requestBody = {
            token: token
          };
    
          return fetch(url, {
              method: 'POST',
              body: JSON.stringify(requestBody)
            })
            .then((response) => response.json())
            .then((responseJSON) => {
              console.log(responseJSON); // <-- this shows the correct JSON data
              resolve(responseJSON);
            }).catch((error) => {
              reject(error);
            });
        });
      });
    }
    

    When calling the fetchFromAPI, use await, like

    const apiData = await fetchFromAPI();
    

    You can also use .then to capture the response and store it in the state, like

    fetchFromAPI.then((data) => {
       // use data here
    });
    

    Hope this will help!