Search code examples
reactjsreduxreact-redux

How to add data in my reducer based on ID


I'm using ReactJS and Redux, and I want to add my data to my reducer but in this way : when I receive my action.payload : it contains ID and DATA property, and the goal is to create(if not exist) a property with ID's value and put the data property into.

Example : When the payload is {111, {name: 'test',age : 25}} , It should create (if not exist) a property in my reducer like this :

MyReducer : {
    clientData : {
       111 : {name : 'test', age : 25}
}
}

And if i want to add another payload : {2222, {name :'toto' : age : 30}} the result should look like :

MyReducer : {
    clientData : {
       111 : {name : 'test', age : 25},
       2222  : {name : 'toto', age : 30}
}
}

And in the case when the id exist in my reducer , it should remplace data with the new action.payload.data values.

I've tried this :

case 'ADD_CLIENT_DATA_SUCCESS':
            const { id, record } = action.payload;
            console.log(action.payload);
            return {
                ...state,
                loading: false,
                clientData: {
                    ...state.clientData,
                    id: record,
                },
            };

But it take id as static variable, the result is this :

enter image description here

Any idea how to achieve this please ? Thank you

EDIT : I've edited my code but for the new data entered, it not rendered as array of object.. This is my code :

case 'ADD_CLIENT_DATA_SUCCESS':
            const { id, record } = action.payload;
            console.log(state.clientData[id]);
            return {
                ...state,
                loading: false,
                clientData: {
                    ...state.clientData,
                    [id]: [state?.clientData[id] || null, record],
                },
            };

Expected result when adding NEWDATA to existed id in my reducer : :

MyReducer : {
    clientData : {
       111 : {name : 'test', age : 25},
       2222  : [{name : 'toto', age : 30}, {name : 'NEWDATA', age : 40}]
}
}


Solution

  • You need to use the id variable as a key so you need to wrap it with []

       case 'ADD_CLIENT_DATA_SUCCESS':
            const { id, record } = action.payload;
            console.log(action.payload);
            return {
                ...state,
                loading: false,
                clientData: {
                    ...state.clientData,
                    [id]: record,
                },
            };
    

    Read Computed property names for more info