camille
camille

Reputation: 328

React Native Updating state in React context API & useState Hook

I have a component with a form, after submitting I want to clear the form values. But its a bit unclear where to empty the form values. Because I have to pass a callback or something from the context to set Form values in the component.

My component with Form

const { updateUserData, state} = useContext(UserContext);

const [name, setName] = useState(state.name);
const [age, setAge] = useState(state.age);

<Input
  value={name}
  label='Enter Name'
  placeholder=''
  onChangeText={(value) => setName(value)}
/>
<Input
  value={age}
  label='Enter Age'
  placeholder=''
  onChangeText={(value) => setAge(value)}
/>

<Button
  onPress={() => {
    let formData = { name, age }
    updateUserData(formData)
  }}>
Update Data
</Button>

My context & Reducer in a separate file

const updateUserData= (dispatch) => async (formData) => {
  // Validation functions
  // If validation fails the name and age values cannot be changed
  if(!valid){
    dispatch({ type: 'NOT_VALID', payload: // errors to be shown })
  }

  // Some API functions
  dispatch({ type: 'RESET_FORM' })
}

const userReduucer= (state, action) => {
  switch (action.type) {
    case 'RESET_FORM':
      return {
        ...state,
        name: '',
        age: '',
      };
  }
}

export const { Context, Provider } = createDataContext(
    userReduucer,
    { updateUserData },
    { name: '', age: '' },
)

Upvotes: 2

Views: 466

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282110

The name and age values are being changed locally, so you need to reset the states locally too and not just in redux store

<Button
  onPress={() => {
    let formData = { name, age }
    updateUserData(formData);
    setName('');
    setAge('');
  }}>

However since you run validations on valued in updateUserData, you could write a useEffect which updates the local values to that of the reducer

    useEffect(() => {
        setName(state.name);
        setAge(state.age);
    }, [state.name, state.age])

   ...
   <Button
      onPress={() => {
        let formData = { name, age }
        updateUserData(formData);
      }}>

Upvotes: 2

Related Questions