How to keep initialState before onChange with reactHookForm

Viewed 23

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.

1 Answers

Resolved :

So for my case (i have multiple value to dispatch) I have removed the "name" in "fetchData" and I have created another function in my slice.

Then i've made the onChange directly in my input

    export const Name = ({ register }) => {
      return (  
    <form> 
        <div >
          <label  >Enter your name </label>
          <input
            {...register('name')}
            type="text"
            name="name" 
            onChange={(e) => dispatch(changeName(e.target.value)}
          />
          <br />
        </div>
            </form>
      );
    };
Related