Check one from the array of checkboxes

682 views Asked by At

My quest is to load array of allergies from an URL and construct one checkbox per allergy. Though somehow after click on any of them, checkbox does not get checked, although the underlying allergies array is changed and reflects the "checked" attribute change. I must be overlooking something trivial.

My React Native component:

import React, { useState, useContext, useEffect } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import { Button, CheckBox } from 'react-native-elements';
import { OnboardingContext } from "../context/onboarding_context";

export function AllergyScreen({ navigation }) {
  const [isLoading, setLoading] = useState(true);
  const [allergies, setAllergies] = useState([]);
  const [state, setState] = useContext(OnboardingContext);

  useEffect(() => {
    fetch('https://foodstuff.com/api/allergies.json')
      .then((response) => response.json())
      .then((json) => setAllergies(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>CATEGORY: {state.category.name}</Text>
      <View style={{ flex: 1, padding: 24 }}>
          <FlatList
            data={allergies}
            keyExtractor={item => item.id.toString()}
            renderItem={({ item }) => (
              <CheckBox
                center
                title={item.name}
                checked={item.checked}
                onPress={() => {
                    item.checked = !item.checked;
                    Object.assign(allergies[allergies.findIndex(element => element.id === item.id)], item)
                    setAllergies(allergies);
                  }
                }
              />
            )}
          />
      </View>
    </View>
  );
}

Allergies:

Array [
  Object {
    "checked": true,
    "created_at": "2020-11-14T10:35:18.883Z",
    "id": 1,
    "name": "Walnuts",
    "updated_at": "2020-11-14T10:35:18.883Z",
  },
  Object {
    "checked": false,
    "created_at": "2020-11-14T10:35:25.345Z",
    "id": 2,
    "name": "Avocado",
    "updated_at": "2020-11-14T10:35:25.345Z",
  },
  Object {
    "checked": false,
    "created_at": "2020-11-14T10:35:31.829Z",
    "id": 3,
    "name": "Bad people",
    "updated_at": "2020-11-14T10:35:31.829Z",
  },
]
1

There are 1 answers

0
Nooruddin Lakhani On BEST ANSWER

Try this way

const onCheck = (index) => {
  const newData = [...allergies];
  newData[index].checked = !newData[index].checked;
  setAllergies(newData);

}   

renderItem={({ item, index }) => (
  <CheckBox
    ......
    onPress={() => { onCheck(index); }
    }
  />
)}