Search code examples
react-nativereact-native-flatlist

Cannot change the value of a Switch within a ListItem in a ReactNative application


In a FlatList I display ListItem elements. Each ListItem has a Text and a Switch. Each time the focus is on the screen, the list of elements is retrieved via an API call.

I have a problem trying to change the value of a ListItem's Switch, the onValueChanged is not triggered and the Switch always come back to its initial value.

I am using the code below. Any idea what I'm missing here ?

function Item({ name, active }) {
  const [act, setAct] = useState(active);

  return (
    <ListItem
        title={ name }
        hideChevron
        switch={
          <Switch
            onValueChange={(v) => {  updateActivation(name, v) }} // API call to change the item's value. This method does not seem to be called !!
            value={act}
           />
        }
        bottomDivider
      />
  );
};

export function ListScreen({ navigation }) {
  const [error, setError] = useState(null);
  const [elements, setElements] = useState([]);

  // Update the list of elements each time the focus comes to the current screen
  // This part is working fine
  useFocusEffect(
    React.useCallback(() => {
      console.log("screen focused => update list of elements")
      async function elements() {
        await getElements();
      }
      elements();
    }, [])
  );

  async function getElements() {
    try {
      let response = await api.getElements();
      setElements([...response]);
    }  catch (error) {
      console.log(error)
    }
  }

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={elements}
        keyExtractor={item => item.name}
        renderItem={({ item }) =>
          <Item name={item.name}
                active={item.active}
          />
        }
      />
    </SafeAreaView>
  );
};

Solution

  • Changing the definition of the switch fixed the thing. The onValueChange is correctly triggered in that case.

    <ListItem
            title={ name }
            hideChevron
            switch={{
                onValueChange: (v) => {  updateActivation(name, v) } // API call to change the item's value. This method does not seem to be called !!
                value: act
            }}
            bottomDivider
    />