I want to change values of two my inputs in Redux, but for some reasons it does not work.
// My code in component
<Input label="name" value={initialUser.name} onChange={(e) => dispatch(onChangeInputAction(e))} name="name" />
<Input label="username" value={initialUser.userName} onChange={(e) => dispatch(onChangeInputAction(e))} name="userName" />
// code from redux
const initialUser: IInitialUser = {
name: '',
userName: '',
id: null,
};
case CustomersActionsEnum.ONCHANGE_INPUT:
const {value, name} = action.payload.currentTarget;
return {...state, initialUser: {...initialUser, [name]: value}};
//action creator
export const onChangeInputAction = (payload:React.FormEvent<HTMLInputElement>) => ({type: CustomersActionsEnum.ONCHANGE_INPUT, payload});
I read that the best idea is to use name from input as a key, I follow this piece of advise, but it does not work.
The problem when I write something in one input, everything is ok, but when I start to write in another input, first input gets clear and the value appears only in the second input.
It looks like you are overwriting state.initialUser
with const initialUser
.
You probably meant to spread ...state.initialUser
const initialUser: IInitialUser = {
name: '',
userName: '',
id: null,
};
case CustomersActionsEnum.ONCHANGE_INPUT:
const {value, name} = action.payload.currentTarget;
return {...state, initialUser: {...state.initialUser, [name]: value}};