Skip to content

Instantly share code, notes, and snippets.

@zaslavskij
Created June 2, 2020 06:46
Show Gist options
  • Select an option

  • Save zaslavskij/d46fe02065d504af5d41591e627b53ec to your computer and use it in GitHub Desktop.

Select an option

Save zaslavskij/d46fe02065d504af5d41591e627b53ec to your computer and use it in GitHub Desktop.
failed to update state
import React from {useEffect, useState, useReducer} 'react'
const initialState = {
username: 'Ivan',
surname: 'Petrov',
age: 30,
profession: 'developer'
}
const reducerFunction = (acc, rec) => {
switch(rec.type) {
case 'UPDATE_USER':
const {user} = rec
return {...acc, ...user}
default: return acc
}
}
const Users = () => {
const [store, dispatch] = useReducer(reducerFunction, initialState)
const [user, setUser] = useState(initialState)
useEffect(() => {
dispatch({type: 'UPDATE_USER', user: {username: 'Petr', surname: 'Ivanon'}})
}, [])
setUser({...user, ...store})
return <div>
{user.username}
<br />
{user.surname}
<br />
{user.age}
<br />
{user.profession}
<br />
</div>
}
ReactDOM.render(<Users />, mountNode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment