Language used : JS with REACT - REDUX TOOLKIT (and in this case react hook form)
Here is the context: I have a form, when the user change something i get the change with redux-toolkit
Here is my problem : In react hook form, you can use register to update the state in a form with'onChange'. But here i'm using 'watch' (because of a radio button issue) and it's working. So i watch and everytime someting is changing, I dispatch my data. But on the first load, react hook form watch and dispatch and i loose my initial state
Here a part of my code with the watch action
const {
register,
watch,
} = useForm();
const data = watch(); // when pass nothing as argument, you are watching everything
useEffect(() => {
dispatch(
fetchData({
name: data.name,
//here i'm watching but loosing my initial state a the first render
})
);
);
}, [data, dispatch]);
Here my form with the register
import React from 'react';
export const Name = ({ register }) => {
return (
<form>
<div >
<label >Enter your name </label>
<input
{...register('name')}
type="text"
name="name"
/>
<br />
</div>
</form>
);
};
here my slice with the initial state
const InfosSlice = createSlice({
name: 'infos',
initialState: {
UserInfos: {
name: 'Lydia',
},
},
reducers: {
fetchData: (state, action) => {
state.UserInfos.name= action.payload?.name;
},
},
});
export const infosReducer = InfosSlice .reducer;
export const {
-
fetchData,
} = InfosSlice.actions;
In redux Devtools, in the frst load i see that i have the initial state
UserInfos: {
name: 'Lydia',
},
and then after the first watch with fetchData i only have
UserInfos: {
},
How can i keep my initial state ? I was thinking about something like "watch" but only changing when the initial value is changing
ps : I have simplified my code for this question but in my project i have a form with multiple step, a lot of data etc.