react#useReducer TypeScript 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: index.tsx From react-doc-viewer with Apache License 2.0 | 6 votes |
PDFProvider: FC<{ mainState: IMainState }> = ({
children,
mainState,
}) => {
const [state, dispatch] = useReducer<PDFStateReducer>(reducer, {
...initialPDFState,
mainState,
});
return (
<PDFContext.Provider value={{ state, dispatch }}>
{children}
</PDFContext.Provider>
);
}
Example #2
Source File: SessionsDataProvider.tsx From caritas-onlineBeratung-frontend with GNU Affero General Public License v3.0 | 6 votes |
export function SessionsDataProvider(props) {
const [sessionsData, dispatchSessionsData] = useReducer(
reducer,
initialState
);
const setSessionsData = (data) => {
dispatchSessionsData({ type: SET_SESSIONS, data: data });
};
return (
<SessionsDataContext.Provider
value={{ sessionsData, setSessionsData, dispatchSessionsData }}
>
{props.children}
</SessionsDataContext.Provider>
);
}
Example #3
Source File: metamask.tsx From metamask-snap-polkadot with Apache License 2.0 | 6 votes |
MetaMaskContextProvider = (props: PropsWithChildren<{}>) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<MetaMaskContext.Provider value={[state, dispatch]}>
{props.children}
</MetaMaskContext.Provider>
);
}
Example #4
Source File: NotionFilter.tsx From Nishan with MIT License | 6 votes |
function NotionFilter(props: Props) {
const default_group_operator = props.default_group_operator ?? "and";
const [filters, dispatch] = useReducer(notionFilterReducer, props.filters ?? {
filters: [],
operator: default_group_operator
})
return <NotionFilterContext.Provider value={{ filter_item_label: props.filter_item_label ?? false, default_group_operator, filters, dispatch, schema: props.schema, nestingLevel: props.nestingLevel ?? 5 }}>
<ThemeProvider theme={theme}>
<div className="NotionFilter" style={{ fontFamily: "Segoe UI" }}>
<FilterGroup parent_filter={null} filter={filters} trails={[]} />
</div>
</ThemeProvider>
</NotionFilterContext.Provider>
}
Example #5
Source File: realtime.tsx From frames with Mozilla Public License 2.0 | 6 votes |
RealtimeConsumer = ({apiKey, children}: { apiKey: string, children: ReactNode }) => {
const [socket, setSocket] = React.useState<Socket>();
const [state, dispatch] = useReducer(reducer, []);
const {isMounted} = useBasics()
useEffect(() => {
if (apiKey !== '' && isMounted()) {
const socket = new Socket("wss://real-time.maix.ovh/socket", {params: {apiKey}});
socket.connect();
setSocket(socket);
return () => {
dispatch({info: 'socket', socket, params: {}, topic: ''});
};
}
}, [apiKey]);
return (
<RealtimeContext.Provider value={{socket, state, dispatch}}>
{state.map(e => <ChannelComponent {...e} key={e.topic}/>)}
{children}
</RealtimeContext.Provider>
);
}
Example #6
Source File: Modals.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
function Modals<BaseOptions = AntdModalProps>({ children }: ModalsProps) {
const initialState: ModalsOptions<BaseOptions> = useInitState<BaseOptions>();
const reducer: ModalsReducer<BaseOptions> = useInitReducer<BaseOptions>();
const [modalsState, dispatch] = useReducer<ModalsReducer<BaseOptions>>(reducer, initialState);
modalsControlsContainer = useInitModalsControls<BaseOptions>(dispatch);
return (
<>
{renderModals<BaseOptions>(modalsState, dispatch)}
{children}
</>
)
}
Example #7
Source File: hooks.ts From drip-table with MIT License | 6 votes |
useState = <T>(initState: T): [T, (action: SetStateAction<Partial<T>>) => void] => useReducer(
(state: T, action: SetStateAction<Partial<T>>): T => {
const data = typeof action === 'function'
? action(state)
: action;
return { ...state, ...data };
},
initState,
)
Example #8
Source File: useRooms.tsx From cards-against-formality-pwa with BSD 2-Clause "Simplified" License | 6 votes |
export default function useRooms(): [any[], boolean, boolean, boolean] {
const [rooms, dispatch] = useReducer(RoomsReducer, []);
const onEvent = useCallback(({ payload, updateType }: any) => {
switch (updateType) {
case 'created':
dispatch({ type: 'ADD_DATA', data: payload })
break;
case 'updated':
dispatch({ type: 'UPDATE_DATA', data: payload })
break;
case 'removed':
dispatch({ type: 'REMOVE_DATA', data: payload })
break;
default:
break;
}
}, []);
const [socketMapping] = useState({ rooms: onEvent });
const [, disconnected, reconnecting] = useSocket(socketMapping, '/rooms');
// TODO: implement infinite scrolling.
const [res, isLoading] = useFetchData<{ rows: any[] }>(`/api/rooms?pageSize=100`);
useEffect(() => {
if (res) {
dispatch({ type: 'MULTI_ADD_DATA', data: res.rows })
}
}, [res]);
return [rooms, isLoading, disconnected, reconnecting];
}
Example #9
Source File: index.tsx From chartsy with GNU General Public License v3.0 | 6 votes |
ImageGridProvider: React.FC = ({ children }) => {
const { titles, setTitles, lastUsed } = useTitles();
const [state, dispatch] = useReducer(ImageGridReducer, titles[lastUsed].imageGrid);
useEffect(() => {
const t = [...titles];
t[lastUsed].imageGrid = state;
setTitles(t);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]);
return <ImageGridContext.Provider value={{ imageGrid: state, dispatch }}>{children}</ImageGridContext.Provider>;
}
Example #10
Source File: useLocalStorage.tsx From Tachidesk-WebUI with Mozilla Public License 2.0 | 6 votes |
export function useReducerLocalStorage<S, A>(
reducer: Reducer<S, A>,
key: string,
defaultState: S | (() => S),
) {
const [storedValue, setValue] = useLocalStorage(key, defaultState);
return useReducer((state: S, action: A): S => {
const newState = reducer(state, action);
setValue(newState);
return newState;
}, storedValue);
}
Example #11
Source File: provider.tsx From useDApp with MIT License | 6 votes |
/**
* @internal Intended for internal use - use it on your own risk
*/
export function BlockNumberProvider({ children }: Props) {
const { library, chainId } = useEthers()
const [state, dispatch] = useReducer(blockNumberReducer, {})
const { isActive } = useWindow()
useEffect(() => subscribeToNewBlock(library, chainId, dispatch, isActive), [library, chainId, isActive])
const debouncedState = useDebounce(state, 100)
const blockNumber = chainId !== undefined ? debouncedState[chainId] : undefined
return <BlockNumberContext.Provider value={blockNumber} children={children} />
}
Example #12
Source File: OBS.tsx From Oratio with MIT License | 6 votes |
export default function OBS() {
const [state, dispatch] = useReducer(reducer, { phrases: [] });
// Only register ipc speech callback once after component is mounted
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ipc.on('speech', (_event: any, message: any) => {
const key: string = uniqueHash();
dispatch({ type: 'push', phrase: { message, key } });
});
}, []);
const classes = useStyles();
return (
<div className={classes.root}>
<div className={classes.textTable}>
<div className={classes.text}>
<div
className={
state.phrases.length <= 0 ? classes.hidden : classes.bubble
}
>
{state.phrases.map((phrase: { message: string; key: string }) => {
return (
<SpeechPhrase
key={phrase.key}
message={phrase.message}
dispatch={dispatch}
/>
);
})}
</div>
</div>
</div>
</div>
);
}
Example #13
Source File: AppContext.tsx From v2 with MIT License | 6 votes |
AppProvider: React.FC<AppProviderInterface> = ({
config,
isMobile,
children,
}) => {
initialState.config = config;
initialState.isMobile = isMobile;
const supportedThemes: string[] = Object.keys(themes);
const localStorageTheme: string | null = localStorage.getItem('theme');
if (localStorageTheme && supportedThemes.includes(localStorageTheme)) {
initialState.theme = themes[localStorageTheme];
}
const [state, dispatch] = useReducer(reducer, initialState);
const value = {
config: state.config,
isMobile: state.isMobile,
theme: state.theme,
setTheme: (value: string) => {
dispatch({ type: actions.SET_THEME, value });
},
};
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}
Example #14
Source File: ModalContext.tsx From convoychat with GNU General Public License v3.0 | 6 votes |
ModalProvider: React.FC = ({ children }) => {
const [state, dispatch] = useReducer(modalReducer, {});
return (
<ModalContext.Provider
value={{
dispatch,
state,
}}
>
{children}
</ModalContext.Provider>
);
}
Example #15
Source File: useFormField.ts From aqualink-app with MIT License | 6 votes |
useFormField = (
initialValue: string | null | undefined,
checks: (
| "required"
| "maxLength"
| "isInt"
| "isNumeric"
| "isLong"
| "isLat"
| "isEmail"
)[],
draftValue?: string,
extraHandler?: (value: string) => void
): [FormField, (value: string, runExtraHandler?: boolean) => void] => {
const reducer = (_state: FormField, newValue: string): FormField => ({
value: newValue,
error: checks
.map((check) => validators[check](newValue))
.filter((error) => error)[0],
});
const [field, dispatch] = useReducer(reducer, { value: initialValue || "" });
useEffect(() => {
if (draftValue) {
dispatch(draftValue);
}
}, [draftValue]);
const handleFieldChange = (value: string, runExtraHandler = false) => {
dispatch(value);
if (extraHandler && runExtraHandler) {
extraHandler(value);
}
};
return [field, handleFieldChange];
}
Example #16
Source File: AppCtx.tsx From hub with Apache License 2.0 | 6 votes |
function AppCtxProvider(props: Props) {
const activeProfilePrefs = lsPreferences.getActiveProfile();
const [ctx, dispatch] = useReducer(appReducer, {
user: undefined,
prefs: activeProfilePrefs,
});
const [activeInitialTheme, setActiveInitialTheme] = useState<string | null>(null);
useEffect(() => {
const theme =
activeProfilePrefs.theme.configured === 'automatic'
? detectActiveThemeMode()
: activeProfilePrefs.theme.configured;
themeBuilder.init();
updateActiveStyleSheet(theme);
setActiveInitialTheme(theme);
refreshUserProfile(dispatch);
}, []); /* eslint-disable-line react-hooks/exhaustive-deps */
useSystemThemeMode(ctx.prefs.theme.configured === 'automatic', dispatch);
if (isNull(activeInitialTheme)) return null;
return <AppCtx.Provider value={{ ctx, dispatch }}>{props.children}</AppCtx.Provider>;
}
Example #17
Source File: index.tsx From simulator with Apache License 2.0 | 6 votes |
function Editor(props: EditorPropsType): JSX.Element {
const [state, dispatch] = useReducer(editorReducer, defaultEditorState);
return (
<EditorContext.Provider value={{ state, dispatch }}>
<TitleBar icon={icon} menu={template} />
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'row',
}}
className="MainContentArea"
>
<ScenarioWorkbench />
</div>
</EditorContext.Provider>
);
}
Example #18
Source File: useLogin.ts From test with BSD 3-Clause "New" or "Revised" License | 6 votes |
useLogin = () => {
const [state, dispatch] = useReducer(reducer, initialState)
const onChangeCsrfToken = useCallback(
value => dispatch({ type: 'CHANGE', field: 'csrfToken', value }),
[],
)
const onChangeIdentifier = useCallback(
value => dispatch({ type: 'CHANGE', field: 'identifier', value }),
[],
)
const onChangePassword = useCallback(
value => dispatch({ type: 'CHANGE', field: 'password ', value }),
[],
)
const onSignIn = useCallback(
event => {
Object.keys(state).forEach(key => {
const hiddenInput = document.createElement('input')
hiddenInput.type = 'hidden'
hiddenInput.name = key === 'csrfToken' ? 'csrf_token' : key
hiddenInput.value = state[key]
event.target.appendChild(hiddenInput)
})
},
[state],
)
return {
...state,
onChangeCsrfToken,
onChangeIdentifier,
onChangePassword,
onSignIn,
}
}
Example #19
Source File: index.tsx From amazon-chime-live-events with Apache License 2.0 | 6 votes |
MetaStateProvider: React.FC = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>
{children}
</DispatchContext.Provider>
</StateContext.Provider>
);
}
Example #20
Source File: UIStateProvider.tsx From amazon-chime-sdk-classroom-demo with Apache License 2.0 | 6 votes |
export default function UIStateProvider(props: Props) {
const { children } = props;
const UIStateContext = getUIStateContext();
return (
<UIStateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</UIStateContext.Provider>
);
}
Example #21
Source File: useLoading.tsx From backstage with Apache License 2.0 | 6 votes |
LoadingProvider = ({ children }: PropsWithChildren<{}>) => {
const classes = useStyles();
const actions = INITIAL_LOADING_ACTIONS;
const [state, dispatch] = useReducer(reducer, getDefaultState(actions));
const [isBackdropVisible, setBackdropVisible] = useState(false);
useEffect(() => {
function displayLoadingBackdrop() {
// Initial page loading is handled by progress bar
setBackdropVisible(
!state[DefaultLoadingAction.CostInsightsInitial] &&
Object.values(state).some(l => l),
);
}
displayLoadingBackdrop();
}, [state, setBackdropVisible]);
return (
<LoadingContext.Provider value={{ state, actions, dispatch }}>
{children}
<Backdrop open={isBackdropVisible} classes={classes}>
<CircularProgress />
</Backdrop>
</LoadingContext.Provider>
);
}
Example #22
Source File: context.tsx From platform with MIT License | 6 votes |
AuthProvider = ({ children }) => {
const [user, dispatch] = useReducer(AuthReducer, initialState);
return (
<AuthStateContext.Provider value={user}>
<AuthDispatchContext.Provider value={dispatch}>
{children}
</AuthDispatchContext.Provider>
</AuthStateContext.Provider>
);
}
Example #23
Source File: useRects.ts From dnd-kit with MIT License | 6 votes |
export function useRects(
elements: Element[],
measure: (element: Element) => ClientRect = getClientRect
): ClientRect[] {
const [firstElement] = elements;
const windowRect = useWindowRect(
firstElement ? getWindow(firstElement) : null
);
const [rects, measureRects] = useReducer(reducer, defaultValue);
const resizeObserver = useResizeObserver({callback: measureRects});
if (elements.length > 0 && rects === defaultValue) {
measureRects();
}
useIsomorphicLayoutEffect(() => {
if (elements.length) {
elements.forEach((element) => resizeObserver?.observe(element));
} else {
resizeObserver?.disconnect();
measureRects();
}
}, [elements]);
return rects;
function reducer() {
if (!elements.length) {
return defaultValue;
}
return elements.map((element) =>
isDocumentScrollingElement(element)
? (windowRect as ClientRect)
: new Rect(measure(element), element)
);
}
}
Example #24
Source File: useTestimonyAttachment.ts From advocacy-maps with MIT License | 6 votes |
export function useDraftTestimonyAttachment(
uid: string,
draft: DraftTestimony | undefined,
setTestimony: SetTestimony
) {
const [state, dispatch] = useReducer(reducer, {
uid,
status: "ok",
attachment: {}
})
useSyncDraft(state, dispatch, draft)
const remove = useRemove(state, dispatch, setTestimony)
const upload = useUpload(state, dispatch, setTestimony)
const {
attachment: { error, id, url, name, size },
status
} = state
return useMemo(
() => ({
remove,
upload,
status,
error,
id,
url,
name,
size
}),
[error, id, name, remove, size, status, upload, url]
)
}
Example #25
Source File: TransactionsProvider.tsx From PolkaBridge-Farming with MIT License | 6 votes |
TransactionsProvider: React.FC = ({ children }) => {
const [{ initialized, transactions }, dispatch] = useReducer(reducer, initialState)
const handleAddTransaction = useCallback((tx: Transaction) => {
dispatch(addTransaction(tx))
}, [dispatch])
const fetchTransactions = useCallback(async () => {
try {
const txsRaw = localStorage.getItem('transactions')
const txs = JSON.parse(txsRaw) as TransactionsMap || {}
dispatch(setTransactions(txs))
} catch (e) {
console.log(e)
}
}, [dispatch])
useEffect(() => {
if (initialized) {
localStorage.setItem('transactions', JSON.stringify(transactions))
}
}, [initialized, transactions])
useEffect(() => {
fetchTransactions()
}, [fetchTransactions])
return (
<Context.Provider value={{
transactions,
onAddTransaction: handleAddTransaction,
}}>
{children}
</Context.Provider>
)
}
Example #26
Source File: context.tsx From homebase-app with MIT License | 6 votes |
CreatorProvider: React.FC = ({ children }) => {
const [data, updateCache] = useLocalStorage<MigrationParams>(
LOCAL_STORAGE_KEY,
INITIAL_STATE.data
);
const stateWithCache = {
...INITIAL_STATE,
data,
};
const [state, dispatch] = useReducer(reducer, stateWithCache);
const contextValue = useMemo(() => {
return { state, dispatch };
}, [state, dispatch]);
return (
<CreatorContext.Provider value={{ ...contextValue, updateCache }}>
{children}
</CreatorContext.Provider>
);
}
Example #27
Source File: context.tsx From covidnet_ui with GNU Affero General Public License v3.0 | 6 votes |
AppProvider: React.FC = ({ children }) => {
const [state, dispatch] = useReducer(mainReducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
)
}
Example #28
Source File: StoreContext.tsx From nosgestesclimat-site with MIT License | 6 votes |
StoreProvider = ({
children,
reducer,
localStorageKey
}: StoreProviderProps) => {
const computeInitialState = useCallback(
() => reducer(getInitialState(localStorageKey), { type: '@@INIT_STATE' }),
[reducer]
)
const [state, dispatch] = useReducer(reducer, undefined, computeInitialState)
useSafeLocaleStorage(localStorageKey, state)
return (
<StoreContext.Provider value={{ state, dispatch }}>
{children}
</StoreContext.Provider>
)
}
Example #29
Source File: HustlerProvider.tsx From dope-monorepo with GNU General Public License v3.0 | 6 votes |
HustlerProvider = ({
children,
initialHustlerData
}: HustlerProviderProps) => {
const [hustler, dispatchHustler] = useReducer<Reducer<HustlerState, HustlerActions>>(
HustlerReducer,
initialHustlerData || INITIAL_STATE,
);
return (
<HustlerContext.Provider value={hustler}>
<HustlerDispatchContext.Provider value={dispatchHustler}>
{children}
</HustlerDispatchContext.Provider>
</HustlerContext.Provider>
);
}