Skip to content Skip to sidebar Skip to footer

Add State To React Native Dynamically Based On Web Api Using Usestate Hook

I have following problem: I intend to fetch data via web API and on its basis, React Native will render it using FlatList. It will use a child component, in this case (Checkbox). S

Solution 1:

Output:

enter image description here

Here is the working example of an app showing data selection and flow of it to the next screen, implement data fetching, and server-side execution accordingly.

importReact, { useState, useEffect } from'react';
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  CheckBox,
  Button,
  Modal,
} from'react-native';
importConstantsfrom'expo-constants';
import { NavigationContainer } from'@react-navigation/native';
import { createStackNavigator } from'@react-navigation/stack';

// You can import from local filesimportAssetExamplefrom'./components/AssetExample';

// or any pure javascript modules available in npmimport { Card } from'react-native-paper';

const data = [
  {
    id: 0,
    product: 'A',
    price: 30,
    selected: false,
  },
  {
    id: 2,
    product: 'B',
    price: 20,
    selected: false,
  },
  {
    id: 3,
    product: 'C',
    price: 10,
    selected: false,
  },
];

constStack = createStackNavigator();

exportdefaultfunctionApp() {
  return (
    <NavigationContainer><Stack.NavigatorinitialRouteName="Home"><Stack.Screenname="Home"component={HomeScreen} /><Stack.Screenname="Payment"component={PaymentScreen} /></Stack.Navigator></NavigationContainer>
  );
}

functionPaymentScreen({ navigation, route }) {
  const { selected } = route.params;
  return (
    <FlatListdata={selected}renderItem={({item }) => (
        <Cardstyle={{margin:5 }}><Viewstyle={styles.card}><Viewstyle={{flexDirection: 'row',
                width:50,
                justifyContent: 'space-between',
              }}><Text>{item.product}</Text></View><Text>{item.price} USD</Text></View></Card>
      )}
    />
  );
}

functionHomeScreen({ navigation }) {
  const [products, setProducts] = useState(data);
  const [showModal, setShowModal] = useState(false);
  const [selected, setSelected] = useState([]);

  consthandleChange = (id) => {
    let temp = products.map((product) => {
      if (id === product.id) {
        return { ...product, selected: !product.selected };
      }
      return product;
    });
    setProducts(temp);
  };

  constgetSelected = () => {
    let temp = products.filter((product) => product.selected);
    setSelected(products.filter((product) => product.selected));
    console.log(temp);
  };

  useEffect(() => {
    getSelected();
  }, [showModal]);

  return (
    <Viewstyle={styles.container}><ModalanimationType="slide"transparent={true}visible={showModal}><Viewstyle={styles.modalView}><FlatListdata={selected}renderItem={({item }) => (
              <Cardstyle={{margin:5 }}><Viewstyle={styles.card}><Viewstyle={{flexDirection: 'row',
                      width:50,
                      justifyContent: 'space-between',
                    }}><Text>{item.product}</Text></View><Text>{item.price} USD</Text></View></Card>
            )}
          />
          <Text>
            Total :{' '}
            {selected.reduce((acc, curr) => acc + curr.price, 0).toString()}
          </Text><Buttontitle={'BUY'}
            onPress={selected
                ? () => {
                    setShowModal(false);
                    navigation.navigate('Payment', { selected: selected });
                  }
                : setShowModal(false)
            }
          />
        </View></Modal><FlatListdata={products}renderItem={({item }) => (
          <Cardstyle={{margin:5 }}><Viewstyle={styles.card}><Viewstyle={{flexDirection: 'row',
                  width:50,
                  justifyContent: 'space-between',
                }}><CheckBoxvalue={item.selected}onChange={() => {
                    handleChange(item.id);
                  }}
                />
                <Text>{item.product}</Text></View><Text>{item.price} USD</Text></View></Card>
        )}
      />
      <Buttontitle={'ADDTOCART'}
        onPress={() => {
          setShowModal(true);
          console.log(showModal);
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },

  card: {
    padding: 10,
    margin: 5,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  modalView: {
    margin: 20,
    backgroundColor: 'white',
    borderRadius: 20,
    padding: 5,
    justifyContent: 'space-between',
    alignItems: 'center',
    elevation: 5,
  },
});

You can play with the working code here: Expo Snack

Solution 2:

This is simple logic code and you would have to implement it in your way of needed

checkBoxChanged = (index) => {
       const newData = [...this.state.data];
       const newData[index].checked = !newData[index].checked;
       this.setState({data: newData});       
}

{this.state.data((item, i) => {
       return (
         <View>
          .......                                   
          <CheckBox
            ......
            checked={item.checked || false}
             onValueChange={() => this.checkBoxChanged(i)}
          />
          .......  
        </View>
})}

Post a Comment for "Add State To React Native Dynamically Based On Web Api Using Usestate Hook"