javascriptarraysreactjsobject2d-context-api

Edit a property in an array of objects in React based on an ID


I have an array of objects created in the new "Context API" like this ...

const reducer = (state, action) => {
    switch (action.type) {
        case "DELETE_CONTACT":
            return {
                ...state,
                contacts: state.contacts.filter(contact => {
                    return contact.id !== action.payload;
                })
            };
        default:
            return state;
    }
};

export class Provider extends Component {
    state = {
        contacts: [
            {
                id: 1,
                name: "John Doe",
                email: "jhon.doe@site.com",
                phone: "01027007024",
                show: false
            },
            {
                id: 2,
                name: "Adam Smith",
                email: "adam.smith@site.com",
                phone: "01027007024",
                show: false
            },
            {
                id: 3,
                name: "Mohammed Salah",
                email: "mohammed.salah@site.com",
                phone: "01027007024",
                show: false
            }
        ],
        dispatch: action => {
            this.setState(state => reducer(state, action));
        }
    };

    render() {
        return (
            <Context.Provider value={this.state}>
                {this.props.children}
            </Context.Provider>
        );
    }
}

I want to create an action in the "reducer" that allows me to edit each contact's "show" property based on its id that I will pass to the action as a payload, how can I do that?


Solution

  • To avoid array mutation and retain the element position while editing contact you can do this:

    case "EDIT_CONTACT":
        const { id, show } = action.payload;
        const contact = { ...state.contacts.find(c => c.id === id), show };
        return {
           ...state,
           contacts: state.contacts.map(c => {return (c.id !== id) ? c : contact;})        
        };