From 0ffbaa5d3e574ac8c9a13be10c69fe9e3d079ed1 Mon Sep 17 00:00:00 2001 From: Harry Wolff Date: Fri, 17 May 2019 21:31:03 -0400 Subject: [PATCH] finish demo --- .../src/LoginWithContext.js | 124 ++++++++++-------- 1 file changed, 71 insertions(+), 53 deletions(-) diff --git a/videos/why-i-love-usereducer/src/LoginWithContext.js b/videos/why-i-love-usereducer/src/LoginWithContext.js index 7b39ffe..1fadf12 100644 --- a/videos/why-i-love-usereducer/src/LoginWithContext.js +++ b/videos/why-i-love-usereducer/src/LoginWithContext.js @@ -1,4 +1,4 @@ -import React, { useReducer } from 'react'; +import React, { useContext, useMemo } from 'react'; import { useImmerReducer } from 'use-immer'; import { login } from './utils'; @@ -66,6 +66,9 @@ const initialState = { todos, }; +const StateContext = React.createContext(); +const DispatchContext = React.createContext(); + export default function LoginUseContext() { const [state, dispatch] = useImmerReducer(loginReducer, initialState); const { username, password, isLoading, error, isLoggedIn, todos } = state; @@ -84,68 +87,76 @@ export default function LoginUseContext() { }; return ( -
-
- {isLoggedIn ? ( - <> -

Welcome {username}!

- - - ) : ( -
- {error &&

{error}

} -

Please Login!

- - dispatch({ - type: 'field', - fieldName: 'username', - payload: e.currentTarget.value, - }) - } - /> - - dispatch({ - type: 'field', - fieldName: 'password', - payload: e.currentTarget.value, - }) - } - /> - -
- )} -
+ + +
+
+ {isLoggedIn ? ( + <> +

Welcome {username}!

+ + + ) : ( +
+ {error &&

{error}

} +

Please Login!

+ + dispatch({ + type: 'field', + fieldName: 'username', + payload: e.currentTarget.value, + }) + } + /> + + dispatch({ + type: 'field', + fieldName: 'password', + payload: e.currentTarget.value, + }) + } + /> + +
+ )} +
- -
+ +
+ + ); } -function TodoPage({ todos, dispatch }) { +function TodoPage({ todos }) { return (

Todos

{todos.map(item => ( - + ))}
); } -function TodoItem({ title, completed, dispatch }) { +function TodoItem({ title, completed }) { + const dispatch = useContext(DispatchContext); + const state = useContext(StateContext); + // const { isLoggedIn } = state; + const isLoggedIn = true; return (

{title}

@@ -153,9 +164,16 @@ function TodoItem({ title, completed, dispatch }) { - dispatch({ type: 'toggleTodoCompleted', payload: title }) - } + onClick={() => { + if (!isLoggedIn) { + alert('Please login to click this!'); + } + }} + onChange={() => { + if (isLoggedIn) { + dispatch({ type: 'toggleTodoCompleted', payload: title }); + } + }} />