Home > Software design >  Is there a way to use a map inside of another map function?
Is there a way to use a map inside of another map function?

Time:12-01

What I'm trying to do is after a field name, I want to render its type which is in another state as you can see:

my code:

    const FormScreen = ({route}) => {
      const [FieldForm, setFieldForm] = useState([]);
      const [TypeForm, setTypeForm] = useState([]);
    
    useEffect(() => {
      if (userForm.length > 0) {
        return;
      } else {
        setFieldForm(JSON.parse(route.params.paramKey).fields);
        setTypeForm(JSON.parse(route.params.paramKey).type);
        console.log(FieldForm,TypeForm);  // returns me: {"message":["ab","test"],"tipo":["Date","Text"]}
      }
    },[userForm,TypeForm]);   
    return (
      <SafeAreaView style={{flex: 1}}>
        <View>
          <Text>COLLECTION :</Text>
    
          {FieldForm.length > 0 ? (
            FieldForm.map((item) => (          
              <Text key={uuid.v4()}>{item}</Text>
              //Here I want to to map which type is the field(to use conditionals to render) but how can I make it? 
            ))
          ) : (
            <Text key={uuid.v4()}> Loading ...</Text>
          )}
    
        </View>
      </SafeAreaView>
    );
    };

How can I use a map inside of a map to do it, or creating an api call to return the type of the fields?

CodePudding user response:

You can definitely nest the map functions :

const FormScreen = ({route}) => {
      const [FieldForm, setFieldForm] = useState([]);
      const [TypeForm, setTypeForm] = useState([]);
    
    useEffect(() => {
      if (userForm.length > 0) {
        return;
      } else {
        setFieldForm(JSON.parse(route.params.paramKey).fields);
        setTypeForm(JSON.parse(route.params.paramKey).type);
        console.log(FieldForm,TypeForm);  // returns me: {"message":["ab","test"],"tipo":["Date","Text"]}
      }
    },[userForm,TypeForm]);   
    return (
      <SafeAreaView style={{flex: 1}}>
        <View>
          <Text>COLLECTION :</Text>
    
          {FieldForm.length > 0 ? (
            FieldForm.map((item) => (
              <>          
                <Text key={uuid.v4()}>{item}</Text>
                <> {TypeForm.length && TypeForm.map((type) => ( // Return node )) || null};
                </>
              </>
            ))
          ) : (
            <Text key={uuid.v4()}> Loading ...</Text>
          )}
    
        </View>
      </SafeAreaView>
    );
    };
  • Related