0

Here I want to change checkbox status. After clicking to checkbox no change does not appear. But after CTR+S in VS Code the data is updated.

const [data,setData] = React.useState();
React.useEffect(() => {
  DB.select("tasks","*").then(res=>{
    return setData(res);
  });
}, [100])

const complete = (index,id)=>{
    data.forEach((x,k)=>{
        if(k == index){
            x.status = !x.status;
            alert(x.name);
            DB.update("tasks",["status"],[x.status],'id=?',[x.id]).then(r=>{
                console.log(r);
            });
            setData(data);
        }
    });
}

<FlatList
    style={css.list}
    data={data}
    extraData={data}

    renderItem={({ item,index }) => 
        <View style={css.item}>
            <View style={css.textItem}>
                <Text>{item.name}</Text>
                <Checkbox
                    status={item.status ? 'checked': 'unchecked'} 
                    onPress={e=>complete(index,id) }
                />

            </View>

            <View style={css.chip}><Text style={{alignItems: 'center',color: "#009386"}}>Category #1</Text></View>

        </View>}
keyExtractor={data => data.id}
/>
TogrulZade
  • 83
  • 7

1 Answers1

1

You're setting the same data which was on the state. So it won't update.

In addition

It is very bad practice to direct;y mutate the state variable what you're doing in complete function. Use map instead of forEach.

Update your complete function as follows:

const complete = (index, id) => {
    const updatedData = data.map((x, k) => {
        x.status = x.status ? 0 : 1;
        DB.update("tasks", ["status"], [x.status], 'id=?', [x.id]).then(r => {
            console.log(r);
        });
        return x;
    });
    setData(updatedData);
}

As you've told that status contains number 0/1, I'm updating status on check with 0 and 1 unlike you're saving boolean. I code in TS, so I'm always aware of types :)

Siraj Alam
  • 9,217
  • 9
  • 53
  • 65