react#useReducer JavaScript Examples

The following examples show how to use react#useReducer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: use-merger.js    From MDXP with MIT License 6 votes vote down vote up
useMerger = defaultState => {
  return useReducer(
    (state, next) => {
      if (typeof next === 'function') {
        next = next(state);
      }

      return {
        ...state,
        ...next
      };
    },
    defaultState
  );
}
Example #2
Source File: Application.js    From about-1hive with GNU General Public License v3.0 6 votes vote down vote up
export default function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, INITIAL_STATE)

  const updateDarkMode = useCallback(mode => {
    dispatch({
      type: UPDATE_DARKMODE,
      payload: {
        mode
      }
    })
  }, [])

  return (
    <ApplicationContext.Provider value={useMemo(() => [state, { updateDarkMode }], [state, updateDarkMode])}>
      {children}
    </ApplicationContext.Provider>
  )
}
Example #3
Source File: Allowances.js    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
export default function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, {})

  const update = useCallback((networkId, address, tokenAddress, spenderAddress, value, blockNumber) => {
    dispatch({ type: UPDATE, payload: { networkId, address, tokenAddress, spenderAddress, value, blockNumber } })
  }, [])

  return (
    <AllowancesContext.Provider value={useMemo(() => [state, { update }], [state, update])}>
      {children}
    </AllowancesContext.Provider>
  )
}
Example #4
Source File: attribute.context.js    From covid-tracker-material-ui-react with MIT License 6 votes vote down vote up
export function AttributeProvider(props) {
  const [attribute, dispatch] = useReducer(attributeReducer, "confirmed");

  return (
    <AttributeContext.Provider value={attribute}>
      <DispatchAttributeContext.Provider value={dispatch}>
        {props.children}
      </DispatchAttributeContext.Provider>
    </AttributeContext.Provider>
  );
}
Example #5
Source File: Example3.js    From Front-end-learning-to-organize-notes with MIT License 6 votes vote down vote up
function ReducerDemo(){
    const [ count , dispatch ] =useReducer((state,action)=>{
        switch(action){
            case 'add':
                return state+1
            case 'sub':
                return state-1
            default:
                return state
        }
    },0)
    return (
       <div>
           <h2>现在的分数是{count}</h2>
           <button onClick={()=>dispatch('add')}>Increment</button>
           <button onClick={()=>dispatch('sub')}>Decrement</button>
       </div>
    )

}
Example #6
Source File: App.js    From eos-icons-landing with MIT License 6 votes vote down vote up
App = () => {
  const [state, dispatch] = useReducer(iconsReducer, eosIconsState)
  const container = React.useRef(null)
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      <div className='App'>
        <Navigation resetIconSetState={container.current} />
        <div className='app-container'>
          <Router primary={false}>
            <Home path='/' container={container} />
            <Docs path='/docs' />
            <CookiesPage path='/cookies-policy' />
            <ThankYou path='/thankyou' />
            <PageNotFound path='*' />
            <AboutPage path='/about' />
            <TeamPage path='/team' />
            <Cheatsheet path='/cheatsheet' />
          </Router>
          <ScrollToTopBtn />
        </div>
        <CookiesBanner />
        <Footer />
      </div>
    </AppContext.Provider>
  )
}
Example #7
Source File: index.js    From website with MIT License 6 votes vote down vote up
CreateDonationPage = ({ mode, donation }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  // prevent re-rendering
  const contextValue = useMemo(() => {
    return { state, dispatch };
  }, [state, dispatch]);

  return (
    <DonationContext.Provider value={contextValue}>
      <Container>
        <HeadingWrapper>
          <Stack spacing="loose">
            <Heading>What are you donating today?</Heading>
            <Alert icon title="Some additional information" type="info">
              As a donor, you are <b>encouraged</b> to cover the delivery cost (if there is) to the specified location.
              This is to encourage donations of good and usable items to the beneficiaries or organizations.
            </Alert>
          </Stack>
        </HeadingWrapper>

        <Wrapper>
          <CreateDonationPanel mode={mode} donation={donation} />
        </Wrapper>
      </Container>
    </DonationContext.Provider>
  );
}
Example #8
Source File: App.js    From ReactJS-Projects with MIT License 6 votes vote down vote up
App = () => {
  const [todos, dispatch] = useReducer(todoReducer, [])


  return (
    <TodoContext.Provider value={{ todos, dispatch }}>
      <Container fluid>
        <h1>Todo Application</h1>
        <Todos />
        <TodoForm />
      </Container>
    </TodoContext.Provider>
  );
}
Example #9
Source File: GlobalState.js    From Otto with MIT License 6 votes vote down vote up
GlobalStateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(
    (state, newValue) => ({ ...state, ...newValue }),
    initialState
  );
  return (
    <GlobalStateContext.Provider value={state}>
      <DispatchStateContext.Provider value={dispatch}>
        {children}
      </DispatchStateContext.Provider>
    </GlobalStateContext.Provider>
  );
}
Example #10
Source File: auth.js    From 0.4.1-Quarantime with MIT License 6 votes vote down vote up
function AuthProvider(props) {
  const [state, dispatch] = useReducer(authReducer, initialState);

  function login(userData) {
    localStorage.setItem('jwtToken', userData.token);
    dispatch({
      type: 'LOGIN',
      payload: userData
    });
  }

  function logout() {
    localStorage.removeItem('jwtToken');
    dispatch({ type: 'LOGOUT' });
  }

  return (
    <AuthContext.Provider
      value={{ user: state.user, login, logout }}
      {...props}
    />
  );
}
Example #11
Source File: Gallery.js    From dshop with MIT License 6 votes vote down vote up
Provider = ({ children, images, active = 0, onChange }) => {
  const stateReducer = useReducer(reducer, {
    active,
    images,
    scrollEl: useRef(null),
    thumbnailsEl: useRef(null)
  })

  useEffect(() => {
    stateReducer[1]({ active })
  }, [active])

  useEffect(() => {
    if (onChange) {
      onChange(stateReducer[0].active)
    }
  }, [stateReducer[0].active])

  return <Context.Provider value={stateReducer}>{children}</Context.Provider>
}
Example #12
Source File: ubi-card.js    From proof-of-humanity-web with MIT License 6 votes vote down vote up
function AccruedUBI({
  web3,
  accruedPerSecond,
  currentBalanceOf,
  registered,
  ...rest
}) {
  const [, rerender] = useReducer(() => ({}), {});
  const [updatedBalance, setUpdatedBalance] = useState(currentBalanceOf);
  useInterval(() => {
    if (currentBalanceOf && accruedPerSecond && registered)
      setUpdatedBalance((previous) => {
        if (previous) return previous.add(accruedPerSecond);
        return currentBalanceOf.add(accruedPerSecond);
      });

    rerender();
  }, 1000);

  if (
    !registered &&
    currentBalanceOf &&
    currentBalanceOf.lte(web3.utils.toBN(0))
  )
    return <Text {...rest}>0 UBI</Text>;

  return (
    <Text {...rest}>
      {updatedBalance
        ? web3.utils.fromWei(updatedBalance).slice(0, 6)
        : currentBalanceOf &&
          web3.utils.fromWei(currentBalanceOf).slice(0, 6)}{" "}
      UBI
    </Text>
  );
}
Example #13
Source File: Nodux.js    From bicara-hook with GNU General Public License v3.0 6 votes vote down vote up
function Nodux(){
  const initialState = [];
  const AppContext = createContext(initialState);
  const Provider = (props) => {
    const store = useReducer(reducer, initialState); // [state, dispatch]
    return(
      <AppContext.Provider value={store}>
        {props.children}
      </AppContext.Provider>
    )
  }
  const Consumer = AppContext.Consumer
  return {
    Provider,
    Consumer,
    AppContext    
  }
}
Example #14
Source File: LocalStorage.js    From spooky-info with GNU General Public License v3.0 6 votes vote down vote up
export default function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, undefined, init)

  const updateKey = useCallback((key, value) => {
    dispatch({ type: UPDATE_KEY, payload: { key, value } })
  }, [])

  return (
    <LocalStorageContext.Provider value={useMemo(() => [state, { updateKey }], [state, updateKey])}>
      {children}
    </LocalStorageContext.Provider>
  )
}
Example #15
Source File: ProductPage.js    From mattress-store with MIT License 6 votes vote down vote up
ProductPage = props => {
    const { Id } = props.match.params;
    const [userProducts, dispatch] = useReducer(productsReducer, null);
    const {
        isLoading,
        error,
        responseData,
        sendRequest,
        values,
        reqIdentifer,
    } = useHttp();

    useEffect(() => {
        sendRequest(
            `http://localhost:3000/api/products/${Id}`,
            'GET',
            null,
            null,
            'GET_ONE_PRODUCT'
        );
    }, []);

    useEffect(() => {
        setTimeout(() => {
            dispatch({ type: 'SET', products: responseData });
        }, 2000);
    }, [responseData, values, reqIdentifer, isLoading, error]);

    let product = <Spinner color="primary" />;
    if (userProducts !== null)
        product = <ProductInfo productData={userProducts} />;

    return <div>{product}</div>;
}
Example #16
Source File: index.js    From react-material-workspace-layout with MIT License 6 votes vote down vote up
RightSidebar = ({ children, initiallyExpanded, height }) => {
  const [expanded, toggleExpanded] = useReducer(
    (state) => !state,
    initiallyExpanded === undefined
      ? getInitialExpandedState()
      : initiallyExpanded
  )

  useEffect(() => {
    if (initiallyExpanded === undefined) {
      window.localStorage.__REACT_WORKSPACE_LAYOUT_EXPANDED =
        JSON.stringify(expanded)
    }
  }, [initiallyExpanded, expanded])

  const containerStyle = useMemo(() => ({ height: height || "100%" }), [height])

  return (
    <ThemeProvider theme={theme}>
      <Container className={expanded ? "expanded" : ""} style={containerStyle}>
        <Slider className={expanded ? "expanded" : ""}>
          <InnerSliderContent>{children}</InnerSliderContent>
        </Slider>
        <Expander
          onClick={toggleExpanded}
          className={expanded ? "expanded" : ""}
        >
          {expanded ? (
            <ContractIcon className="icon" />
          ) : (
            <ExpandIcon className="icon" />
          )}
        </Expander>
      </Container>
    </ThemeProvider>
  )
}
Example #17
Source File: index.js    From desktop with GNU General Public License v3.0 6 votes vote down vote up
App = () => {
  const useAppState = useReducer(appReducer, initialAppState);
  return (
    <ApolloProvider client={client}>
      <Provider value={useAppState}>
        <AppFrame />
      </Provider>
    </ApolloProvider>
  );
}
Example #18
Source File: themeState.js    From webDevsCom with MIT License 6 votes vote down vote up
ThemeState = props => {
  const intialState = { isDarkMode: JSON.parse(localStorage.getItem("dark-mode")) };

  const [state, dispatch] = useReducer(ThemeReducer, intialState);

  // Toggle Theme
  const toggleTheme = () => {
    dispatch({
      type: TOGGLE_THEME,
      payload: !state.isDarkMode
    })
  }

  useEffect(() => {
    localStorage.setItem("dark-mode", state.isDarkMode)
    if (state.isDarkMode) {
      document.querySelector('body').classList.add('dark-mode');
    } else {
      document.querySelector('body').classList.remove('dark-mode');
    }
  }, [state.isDarkMode]);

  return <ThemeContext.Provider value={{
    isDarkMode: state.isDarkMode,
    toggleTheme
  }}>
    {props.children}
  </ThemeContext.Provider>
}
Example #19
Source File: SignalContext.js    From redparty with GNU General Public License v3.0 6 votes vote down vote up
SignalContextProvider = (props) => {
	const initialState = {
		playVideo: null, // hold video play time
		pauseVideo: null, // hold command timestamp

		// when transition is true, no player related socket event will
		// be emitted to the server. This prevents unintentional back and forth
		// event passing and provides consistency in video seek/pause.
		transition: false,
		videoChanging: false,
	};

	const [signalData, dispatch] = useReducer(signalReducer, initialState);

	return (
		<SignalContext.Provider value={{ signalData, dispatch }}>
			{props.children}
		</SignalContext.Provider>
	);
}
Example #20
Source File: auth.js    From stack-underflow with MIT License 6 votes vote down vote up
AuthProvider = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, { user: null });

  useEffect(() => {
    const loggedUser = storage.loadUser();

    if (loggedUser) {
      dispatch({
        type: 'LOGIN',
        payload: loggedUser,
      });
    }
  }, []);

  const setUser = (userData) => {
    storage.saveUser(userData);
    dispatch({
      type: 'LOGIN',
      payload: userData,
    });
  };

  const logoutUser = () => {
    storage.removeUser();
    dispatch({ type: 'LOGOUT' });
  };

  return (
    <AuthContext.Provider value={{ user: state.user, setUser, logoutUser }}>
      {children}
    </AuthContext.Provider>
  );
}
Example #21
Source File: authState.js    From to-view-list with MIT License 6 votes vote down vote up
AuthStateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, initialState);

  return (
    <AuthContext.Provider value={[state, dispatch]}>
      {children}
    </AuthContext.Provider>
  );
}
Example #22
Source File: useSchema.js    From beautiful-react-diagrams with MIT License 6 votes vote down vote up
useSchema = (initialSchema = initialState) => {
  const [schema, dispatch] = useReducer(schemaReducer, initialSchema);

  const onChange = useCallback(({ nodes, links }) => dispatch({ type: ON_CHANGE, payload: { nodes, links } }), []);
  const addNode = useCallback((node) => dispatch({ type: ON_NODE_ADD, payload: { node: ensureNodeId(node) } }), []);
  const removeNode = useCallback((node) => dispatch({ type: ON_NODE_REMOVE, payload: { nodeId: node.id } }), []);
  const connect = useCallback((input, output) => dispatch({ type: ON_CONNECT, payload: { link: { input, output } } }), []);

  return [schema, Object.freeze({ onChange, addNode, removeNode, connect })];
}
Example #23
Source File: App.jsx    From editable-react-table with MIT License 6 votes vote down vote up
function App() {
  const [state, dispatch] = useReducer(reducer, makeData(1000));

  useEffect(() => {
    dispatch({ type: ActionTypes.ENABLE_RESET });
  }, [state.data, state.columns]);

  return (
    <div
      className="overflow-y-hidden"
      style={{
        width: '100vw',
        height: '100vh',
      }}
    >
      <Table
        columns={state.columns}
        data={state.data}
        dispatch={dispatch}
        skipReset={state.skipReset}
      />
      <div id="popper-portal"></div>
    </div>
  );
}
Example #24
Source File: use-dappy-templates.hook.js    From crypto-dappy with Apache License 2.0 6 votes vote down vote up
export default function useDappyTemplates() {
  const [state, dispatch] = useReducer(defaultReducer, { loading: false, error: false, data: [] })

  useEffect(() => {
    const fetchDappyTemplates = async () => {
      dispatch({ type: 'PROCESSING' })
      try {
        let res = await query({ cadence: LIST_DAPPY_TEMPLATES })
        let mappedDappies = Object.values(res).map(d => {
          return new DappyClass(d?.templateID, d?.dna, d?.name, d?.price)
        })
        dispatch({ type: 'SUCCESS', payload: mappedDappies })
      } catch (err) {
        dispatch({ type: 'ERROR' })
      }
    }
    fetchDappyTemplates()
  }, [])

  return state
}
Example #25
Source File: App.js    From Learning-Redux with MIT License 6 votes vote down vote up
App = () => {
  const [person, dispatch] = useReducer(reducer, data);

  return (
    <div className="App component">
      <PersonContext.Provider value={[person, setName, setLocation, dispatch]}>
        <h1>Main App</h1>
        <SubComponent1 />
      </PersonContext.Provider>
    </div>
  );
}
Example #26
Source File: index.js    From derivcrypto-com with Apache License 2.0 6 votes vote down vote up
StateProvider = ({ children }) => {
    const [state, dispatch] = useReducer((state, action) => {
        switch (action.type) {
            case 'UPDATE_STORE':
                const newState = { ...state, ...action.payload }
                return newState
            default:
                throw new Error()
        }
    }, initialState)

    return <Provider value={{ state, dispatch }}>{children}</Provider>
}
Example #27
Source File: CheckedItemContext.js    From IssueTracker-28 with MIT License 6 votes vote down vote up
// 위에서 선언한 두가지 context들의 provider로 감싸주는 컴포넌트
export function CheckedItemProvider({ children }) {
  const [state, dispatch] = useReducer(checkedItemReducer, initialState);

  return (
    <CheckedItemStateContext.Provider value={state}>
      <CheckedItemDispatchContext.Provider value={dispatch}> {children}</CheckedItemDispatchContext.Provider>
    </CheckedItemStateContext.Provider>
  );
}
Example #28
Source File: MemberContext.jsx    From relay_15 with MIT License 6 votes vote down vote up
export function MemberContextProvider({ children }) {
  const [state, dispatch] = useReducer(memberReducer, {
    loginStatus: '',
    myInfo: {
      email: '',
      name: '',
      friends: [],
    },
    mainInfo: {
      email: '',
      name: '',
      friends: [],
      guestbooks: [],
    },
  });

  return (
    <DispatchContext.Provider value={dispatch}>
      <MemberContext.Provider value={state}>{children}</MemberContext.Provider>
    </DispatchContext.Provider>
  );
}
Example #29
Source File: contact-context.js    From react-crud-app with MIT License 6 votes vote down vote up
ContactContextProvider = (props) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return(
    <ContactContext.Provider value={[state, dispatch]}>
      {props.children}
    </ContactContext.Provider>
  )
}