I have written a reducer code where I check if the same value is already present in the array. If it is, I update the previous value instead of pushing the same value again.
Here is my code snippet:
export function reducer(
state: IDeviceState = initialState,
action: DeviceActions.AllDeviceActions
): IDeviceState {
switch (action.type) {
case DeviceActions.GET_DEVICE_BY_ID_SUCCESS: {
const { payload } = action;
const devices = Array.isArray(payload)
? payload
.map(pushBranches)
.flat()
.filter((device) => device !== null)
: [pushBranches(payload)].filter((device) => device !== null);
const updatedDevices = devices.filter((device) => {
const existingDevice = state.devices.find(
(d) => d.result?.unitId === device.result.unitId
);
return !existingDevice;
});
return {
...state,
devices: state.devices.concat(updatedDevices),
loading: false,
loaded: true,
error: null,
};
}
default: {
return state;
}
}
}
function pushBranches(devices: any) {
if (devices.result) {
return devices;
}
return null;
}