Skip to content

Commit

Permalink
immer
Browse files Browse the repository at this point in the history
  • Loading branch information
wuyawei committed Sep 15, 2020
1 parent a23edb8 commit cced7aa
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
29 changes: 29 additions & 0 deletions react/demo/src/Ability/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import React, { useState, Suspense } from 'react';
import useImmerState from '../hooks/useImmerState';

const baseState = [
{
todo: "Learn typescript",
done: true
},
{
todo: "Try immer",
done: false
}
]
function Ability() {
const [value, setValue] = useImmerState(baseState);
const onClick = () => {
setValue(draftState => {
draftState.push({todo: "Tweet about it"})
draftState[1].done = true
})
}
return (
<div onClick={onClick}>
{JSON.stringify(value)}
</div>
)
}

export default Ability;
4 changes: 3 additions & 1 deletion react/demo/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const Carousel = lazy(() => import('./Carousel'));
const Test = lazy(() => import('./Test/index'));
const ToScroll = lazy(() => import('./ToScroll/index'))
const Lazy = lazy(() => import('./Lazy'))
const Ability = lazy(() => import('./Ability'))

function AppRouter() {
return (
Expand All @@ -34,7 +35,8 @@ function AppRouter() {
<Route path="/carousel" component={Carousel} />
<Route path="/test" component={Test} />
<Route path="/scroll" component={ToScroll} />
<Route path="/lazy" component={Lazy} />
<Route path="/Lazy" component={Lazy} />
<Route path="/ability" component={Ability} />
</Switch>
</Suspense>
</Router>
Expand Down
15 changes: 15 additions & 0 deletions react/demo/src/hooks/useImmerState.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import produce from "immer"

const useImmerState = (initialValue) => {
const [value, setValue] = useState(initialValue);
const setState = useCallback((callback) => {
const nextState = produce(value, draftState => {
callback(draftState);
})
setValue(nextState);
}, [value])
return [value, setState]
}

export default useImmerState;

0 comments on commit cced7aa

Please sign in to comment.