Skip to content

Instantly share code, notes, and snippets.

@AkatQuas
Last active August 15, 2019 08:34
Show Gist options
  • Select an option

  • Save AkatQuas/6039c005bccc6917726fda0324cf505a to your computer and use it in GitHub Desktop.

Select an option

Save AkatQuas/6039c005bccc6917726fda0324cf505a to your computer and use it in GitHub Desktop.

Revisions

  1. AkatQuas renamed this gist Aug 15, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. AkatQuas created this gist Aug 15, 2019.
    59 changes: 59 additions & 0 deletions App.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    import React, { createContext, useReducer, useContext, Fragment } from 'react';
    import './App.css';

    const authReducer = (state, action) => {
    switch (action.type) {
    case 'increment':
    return {
    ...state,
    age: state.age + 1
    };
    case 'login':
    const { name } = action;
    return {
    ...state,
    name,
    };
    default:
    return state;
    }
    }

    const AuthContext = createContext(null);

    const AuthProvider = ({
    children
    }) => {
    const [state, dispatch] = useReducer(authReducer, {
    name: 'yang',
    age: 11,
    });
    return (
    <AuthContext.Provider value={{ state, dispatch }} >
    {children}
    </AuthContext.Provider>
    )
    }

    const NameLabel = (props) => {
    const { state, dispatch } = useContext(AuthContext);

    return (
    <Fragment>
    <p>{state.name} @ {state.age}</p>
    <p>{props.label}</p>
    <button onClick={() => dispatch({ type: 'increment' })}> increment </button>
    <button onClick={() => dispatch({ type: 'login', name: Math.random().toString(16) })}> chang name </button>
    </Fragment>
    )
    }

    function App() {
    return (
    <AuthProvider>
    <NameLabel label="example" />
    </AuthProvider>
    );
    }

    export default App;