I'm starting to learn React + hooks. I'm on useReducer right now. But I'm having problem to update my useReducer state. every time I want to update 1 field on my object state, all other fields will get deleted.
My solution is to pass them all the existing values, even though I only need to update 1 field. Is there more efficient way of doing this?
Here is my solution:
const initialState = {
filter: {
text: "Filter",
list: [],
isActive: false,
message: "",
},
apiList: []
};
const reducer = (state, action) => {
switch (action.type) {
case "SET_FILTER_LIST":
return {
...state,
filter: { ...state.filter,
list: action.payload.list,
isActive: action.payload.isActive,
message: action.payload.message,
text: action.payload.text,
}
};
default:
return state;
}
};
//BELOW - I just want to pass the e.target.textContent to text field. To avoid deleting the other fields. I re-pass all the existing value so it wont get deleted.
const onSelect = e => {
let filter = e.target.textContent;
dispatch({
type: 'SET_FILTER_LIST',
payload: {
list: state.filter.list,
text: filter,
message: state.filter.message,
isActive: state.filter.isActive
}
});
};