Home > Enterprise >  axios response destructuring undefined
axios response destructuring undefined

Time:01-15

export async function downloadAndSyncData(
  user_id: number
): Promise<boolean> {
  try {
    const { status, data } = await getProtocols(user_id);
    let { sets } = data;
    if (status === 200) {
      if (sets !== undefined) {
        console.log("entrou aqui");
        sets.map(async set => {
          const callDetail = detailData(set);
          let obj = await insertDataStorage("DetailSchema", callDetail);
        });
      } else {
        console.log("undefined sets");
      }
      return true;
    } else {
      return false;
    }
  } catch (error) {
    throw error;
  } finally {
    await syncOptions();
  }
}

I have a function on my app that make a request from sets to show on a list. sets is an Array of Objects, that comes from my backend on laravel. laravel return

The thing is, sometimes that work, sometimes not. And i didn't understand why. It works with small objects.

test console

On postman, its ok too. postman

CodePudding user response:

Move destructuring inside if (status === 200) { check. If the status is not 200 then the data might be undefined and you cannot destructure undefined value.

Or you can rewrite your check like that: let sets = data?.sets;, that way you will first check that the data is here, then get sets property value.

  •  Tags:  
  • Related