4

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 };

});

2 Comments

It'd probably be advisable not to mutate item directly here.
@JKillian agreed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.