Home > database >  how to stop a function in if statement in react native?
how to stop a function in if statement in react native?

Time:07-07

I want to use if statement in a function such that **"if there is x ,don't continue function" ** "else ,continue the function".... my code is like below,i dont know why it continue doing the function!(it create calendar) plz help me

const calendars = await Calendar.getCalendarsAsync(
      Calendar.EntityTypes.EVENT
    );
    const filterdcalender = calendars.filter((e) => e.name === "new Calendar");
    if (filterdcalender ==! undefined || filterdcalender ==! null) {
      console.log('✅ Calender already exists');
      console.log({ filterdcalender });
      return;
    } else{const defaultCalendarSource =
      Platform.OS === 'ios'
      ? await getDefaultCalendarSource()
      : { isLocalAccount: true, name: 'new Calendar' };
    //     ///////////////////////////////////////////////////new calendar
    const newCalendarID = await Calendar.createCalendarAsync({
      title: 'Title New Calendar',
      color: 'blue',
      entityType: Calendar.EntityTypes.EVENT,
      sourceId: defaultCalendarSource.id,
      source: defaultCalendarSource,
      name: 'name New Calendar',
      ownerAccount: 'personal',
      accessLevel: Calendar.CalendarAccessLevel.OWNER,
    });
    console.log(`Your new calendar ID is: ${newCalendarID}`);    
  }}

CodePudding user response:

First of all a ==! b isn't doing what you probably think it does. Because semantically it's equivalent to a == (!b). Use !== instead.

Second Array.filter() will never return null or undefined. It will always return an array (which may be empty if no value meeting the condition is found). Thus filteredcalender !== null || fillteredcalendar !== undefined will always be true

You could either check the length of the filtered array

const filterdcalendar = calendars.filter((e) => e.name === "new Calendar");
if (filteredcalendar.length > 0) { 
  //calendar already exists 
  return;
}
else { 
  //create new calendar 
}

Or you could make use of Array.find()

const filterdcalendar = calendars.find((e) => e.name === "new Calendar");
if (filteredcalendar !== undefined) { 
  //calendar already exists 
  return;
}
else { 
  //create new calendar 
}

CodePudding user response:

I would simplify the condition using the nullish coalescing operator. Then refactor your filter because as @derpirscher mentioned, Array.filter will never return null.

  • Related