devon66h
devon66h

Reputation: 557

Why is code being executed before forEach loop finishes?

In the code below, I'm expecting the forEach loop to execute, then initialize the selectedGroup state with data created from the loop.

Upon render of the component, the loop works just fine, but the selectedGroup state doesn't get initialized. It seems that selectedGroup is trying to be initialized before the loop finishes. Any ideas?

Code in Question:

const MenuContent = ({ items, modifiers }) => {
  let groups = [];
  items.forEach((item) => {
    !groups.includes(item.group) && groups.push(item.group);
  });

  const [selectedGroup, setSelectedGroup] = useState(groups[0]);

  return (
    <View style={styles.container}>
      <Text>{selectedGroup}</Text>
    </View>
  );
};

Items Array Used in Code:

Array [
   Object {
       "86": false,
       "description ": null,
       "group": "Liquors",
       "ingredients ": null,
       "modifiers": Array [
      "gh5OdUAQC0bCr9O0HrF8",
       ],
       "name": "Smirnoff",
       "price": 350,
   },
   Object {
       "86": false,
       "description": "Vodka, Passionfruit, Ginger, Lemon",
       "group": "Cocktails",
       "ingredients ": null,
       "modifiers": Array [
         "hzxrMy17xrikXA0yumYB",
         "sLrkn3QXOgOzbHobdIRG",
       ],
       "name": "Passionfruit Mule",
       "price": 1400,
   },
]

Upvotes: 0

Views: 50

Answers (1)

prasanth
prasanth

Reputation: 22500

You could do with useEffect hook

const MenuContent = ({ items, modifiers }) => {

  const [selectedGroup, setSelectedGroup] = useState(null);

  useEffect(()=>{
         let groups = [];
         items.forEach((item) => {
           !groups.includes(item.group) && groups.push(item.group);
         });
         setSelectedGroup(groups[0])
   },[items])

  return (
    <View style={styles.container}>
      <Text>{selectedGroup}</Text>
    </View>
  );
};

if you need to prevent the render until value get assigned. use with && conditional operator on render

 return (
        <View style={styles.container}>
          {selectedGroup && <Text>{selectedGroup}</Text>}
        </View>
      )

Upvotes: 1

Related Questions