Created
August 5, 2019 21:21
-
-
Save behnammodi/81674585fb7179312fb2c3f6ac6414e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer, createContext, useContext, useEffect } from "react"; | |
import { on, emit } from "jetemit"; | |
const initialValue = { X: 0, Y: 0 }; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case "+": | |
return { | |
...state, | |
X: state.X + 1 | |
}; | |
case "-": | |
return { | |
...state, | |
X: state.X - 1 | |
}; | |
case "RESET": | |
return { | |
...state, | |
X: 0 | |
}; | |
default: | |
return state; | |
} | |
}; | |
const Context = createContext(); | |
function Provider({ children }) { | |
const [state, dispatch] = useReducer(reducer, initialValue); | |
useEffect(() => { | |
const unsubscribe = on("dispatch", dispatch); | |
return () => unsubscribe(); | |
}, []); | |
console.log("render Provider"); | |
return <Context.Provider value={state}>{children}</Context.Provider>; | |
} | |
function dispatch(data) { | |
emit("dispatch", data); | |
} | |
function useGlobalState() { | |
return useContext(Context); | |
} | |
function DisplayXA() { | |
const globalState = useGlobalState(); | |
console.log("render DisplayXA"); | |
return ( | |
<div> | |
A: {globalState.X} | |
<button onClick={() => dispatch({ type: "+" })}>+</button> | |
<button onClick={() => dispatch({ type: "-" })}>-</button> | |
<button onClick={() => dispatch({ type: "RESET" })}>Reset</button> | |
</div> | |
); | |
} | |
function DisplayXB() { | |
const globalState = useGlobalState(); | |
console.log("render DisplayXB"); | |
return ( | |
<div> | |
B: {globalState.X} | |
<button onClick={() => dispatch({ type: "+" })}>+</button> | |
<button onClick={() => dispatch({ type: "-" })}>-</button> | |
<button onClick={() => dispatch({ type: "RESET" })}>Reset</button> | |
</div> | |
); | |
} | |
function DisplayNothing() { | |
console.log("render DisplayNothing"); | |
return ( | |
<div> | |
Nothing | |
<button onClick={() => dispatch({ type: "RESET" })}>Reset</button> | |
</div> | |
); | |
} | |
function App() { | |
console.log("render App"); | |
return ( | |
<div> | |
<DisplayXA /> | |
<DisplayXB /> | |
<DisplayNothing /> | |
</div> | |
); | |
} | |
function Boot() { | |
console.log("render Boot"); | |
return ( | |
<Provider> | |
<App /> | |
</Provider> | |
); | |
} | |
export default Boot; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment