mercredi 28 avril 2021

How to create a react native state with key and value array?

I've a flatlist with a list of options and a checkboxes in each row, and I need a state for the checkboxex, using hooks. I tought create a key-value relationship, an associative array somehow, so I can access to the proper state using the "item.option" as key:

export default function Questions({ navigation, route }) {

    const [questionNumber, setQuestionNumber] = useState(0);
    const data = route.params.data;
    const numberOfQuestions = Object.keys(data.questions).length;

    const [selectedOption, setSelectedOption] = useState([null]);
    const [toggleCheckBox, setToggleCheckBox] = useState([false])

    [...]

    const renderItemMultipleChoice = ({ item }) => {
        console.log(toggleCheckBox[item.option],item.option); //******here I get undefined
        return (
            <View style={[styles.option]}>
                <CheckBox style={styles.checkBox}
                    disabled={false}
                    value={toggleCheckBox[item.option]}
                    onValueChange={(newValue) => multipleChoiceHandler(item.option, newValue)}
                />
                <Text style={styles.optionText}>{item.option}</Text>
            </View>

        );
    };

    const multipleChoiceHandler = (item, newValue) => {
        var newHash = toggleCheckBox
        newHash[item] = newValue;
        setToggleCheckBox({toggleCheckBox: newHash});
    }

    useEffect(() => {
        if (data.questions[questionNumber].type_option != "open_choice") {
            for (i = 0; i < Object.keys(data.questions[questionNumber].options).length; i++) {
                var newHash = toggleCheckBox
                newHash[data.questions[questionNumber].options[i].option] = false; 
//*******every checkbox is false at the beginning...
                setToggleCheckBox({toggleCheckBox: newHash});
                console.log("toggle checkbox:",toggleCheckBox[data.questions[questionNumber].options[i].option],
 data.questions[questionNumber].options[i].option); //****** here I get all false, the value I setted. 

            }
            setSelectedOption([null]);
        }
    }, [questionNumber])



     return(
             <FlatList style={styles.flatlistOption}
                    data={data.questions[questionNumber].options}
                    renderItem={renderItemMultipleChoice}
                    keyExtractor={(item) => item.option}
                />
     )
}

I'm supernoob about react, so to insert the intial state of toggleCheckBox for each element (using the parameter option to refer to the proper array element), I've used a for cycle... I know it's not proper and quite spaghetti code. Btw it should work, but when I try to access from the checklist to the toggleCheckBox state I get a undefined, so the checkbox state doesn't work properly. I don't know what I'm missing...




Aucun commentaire:

Enregistrer un commentaire