jesica
jesica

Reputation: 685

React.js state items array not updating properly even not showing any error

At first please see the picture for actually what's going on

enter image description here

The issue is while marked the checkbox then text erasing but I want to update a state field from state array & the functionalities are like below

state = {
    items: [
        { id: 1, text: 'Buy milk', done: true },
        { id: 2, text: 'Deed cat', done: false },
        { id: 3, text: 'Wash floor', done: false }
    ]
};

markItemDone = (i) => {
    this.setState(state => {
        const items = state.items.map((item) => {
            if (item.id === i){
                return item.done = true;
            } else {
                return item;
            }
        });

        return {
            items,
        };
    });
}

JSX:

 <input 
    type="checkbox" 
    onClick={() => this.markItemDone(item.id)}
    defaultChecked={item.done ? true : null}
 />

I'm not finding the actual solution.

Thanks

Upvotes: 4

Views: 408

Answers (2)

Dacre Denny
Dacre Denny

Reputation: 30360

This line in your map callback:

return item.done = true; 

will map item to undefined for the item where id === i. Try revising your map callback as shown:

const items = state.items.map((item) => {

    /* Return copy of item. If id === item.id, add done : true to 
        mapped result. For all other cases, ensure done is undefined */ 
        return { ...item, done : id === item.id ? true : undefined };

});

Upvotes: 0

JKillian
JKillian

Reputation: 18351

In your code, you say return item.done = true;. This is returning a boolean instead of an item object and thus why you see 1: true in your screenshot. Instead, you want something like this:

        if (item.id === i){
            return {
                ...item,
                done: true,
            };
        } else {
            return item;
        }

This will make a copy of the original item object, set its done field to be true, and return the new item.

Upvotes: 4

Related Questions