Reputation: 1655
I have a question is this code correct? State in React is inmutable so this is correct or not?
case "GET_SINGLE":
const newState = [...state.data];
const id = action.payload;
const item = newState.filter((item) => item.id === id.id);
return {
...state,
record: item[0],
};
Upvotes: 0
Views: 41
Reputation: 42170
Your state has a property data
with an array of objects and a property record
with the current object. If you are looking on opinions of the state structure, I think this is an unnecessary duplication. You could just save the id of the current record and use a selector to get the whole object. It's not good to have the same data in multiple places because you want a single source of truth.
But as far as this selector is concerned, you are finding the item which matches the id
from the action.payload
and saving it the the property record
. You are only looking for one item so you should use find()
instead of filter()
.
Using the variable id.id
is very confusing. You can use destructuring to get just the id
from the payload (const {id} = action.payload;
). Or you could just use action.payload.id
in your comparison (item.id === action.playload.id
).
case "GET_SINGLE":
const {id} = action.payload;
const item = state.data.find((item) => item.id === id);
return {
...state,
record: item,
};
Upvotes: 1