how to store registered user data in reducer react?

Viewed 27
 const initialUser = {
        name: '',
        email: '',
        updated_at: '',
        created_at: '',
        id: ''
    }


  dispatch({type: 'user_register',payload: user })

As you can see my initialState and dispatch . I want my user to be stored in state. Everything is working good. I cant change my state from initialState to user.

1 Answers

From your reducer you should always return a new Object

    const reducer = (state, action) => {
      switch(action.type){
      case 'user_register':
      console.log(action.payload, state)
      return {
        ...state,
        name:action.payload.name, 
        email:action.payload.email
      }
    
    }
  }

export function App(props) {
   const initialUser = {
        name: '',
        email: '',
        updated_at: '',
        created_at: '',
        id: ''
    }
  const [state, dispatch] = React.useReducer(reducer, initialUser)

  React.useEffect(() => {
    dispatch({type: 'user_register',payload: {name:"Testing", email:"testing@test.com"} }) // you can send your values which needs to be updated
  },[])

  React.useEffect(() => {
    console.log(state)
  },[state])
  return (
    <div className='App'>
    </div>
  );
}

I hope this example will resolve your query.

Related