react#Dispatch TypeScript Examples

The following examples show how to use react#Dispatch. 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: TextField.tsx    From natds-rn with ISC License 7 votes vote down vote up
statusActiveHandler = (
  event: (e: NativeSyntheticEvent<TextInputFocusEventData>) => void,
  nativeEvent: NativeSyntheticEvent<TextInputFocusEventData>,
  status: boolean,
  setActive: Dispatch<SetStateAction<boolean>>
) => {
  setActive(status)
  if (event) event(nativeEvent)
}
Example #2
Source File: utilities.ts    From react-pokedex with MIT License 7 votes vote down vote up
wrapReduxAsyncHandler = (
  statusHandler: StatusHandler,
  callback: (dispatch: Dispatch<any>, args: any) => Promise<void>
) => (args?: any) => async (dispatch: Dispatch<any>) => {
  dispatch(statusHandler.initialize({}));

  callback(dispatch, args)
    .then(() => {
      dispatch(statusHandler.success({}));
    })
    .catch((err) => {
      console.error(err);
    });
}
Example #3
Source File: Switch.tsx    From Demae with MIT License 6 votes vote down vote up
useSwitch = (initValue: boolean, props: SwitchProps = {}): [SwitchProps, Dispatch<SetStateAction<boolean>>] => {
	const [value, setValue] = useState<boolean>(initValue)

	useEffect(() => setValue(initValue), [])

	const onChange = props.onChange || ((e: React.ChangeEvent<HTMLInputElement>) => {
		const value = e.target.value as unknown as boolean
		setValue(value)
	})

	return [{ value, onChange, ...props } as SwitchProps, setValue]
}
Example #4
Source File: action.ts    From wiregui with MIT License 6 votes vote down vote up
export function fetchFiles(userDataPath: string) {
  return async function(dispatch: Dispatch<unknown>) {
    const configPath = path.join(
      userDataPath,
      "configurations"
    );
  
    if (!fs.existsSync(configPath)) {
      fs.mkdirSync(configPath);
    }
  
    const activeTunnelName = await getActiveTunnelName();
    const filenames = fs.readdirSync(configPath);
    const files = await Promise.all(
      filenames.map(async (filename: string) => {
        const filePath = path.join(configPath, filename);
        const config = new WgConfig({ filePath });
        await config.parseFile();

        const name = filename.split(".")[0];
        const lastConnectAt = localStorage.getItem(name);
        return {
          name,
          path: filePath,
          address: config.wgInterface.address,
          lastConnectAt,
          active: name === activeTunnelName,
        };
      })
    );

    dispatch(updateStatus(activeTunnelName));
    dispatch(fetchFilesSuccess(files));
  }
}
Example #5
Source File: useDeepEqualState.ts    From react-datasheet-grid with MIT License 6 votes vote down vote up
useDeepEqualState = <T>(
  defaultValue: T
): [T, Dispatch<SetStateAction<T>>] => {
  const [value, setValue] = useState<T>(defaultValue)

  const customSetValue = useCallback(
    (newValue: SetStateAction<T>) => {
      setValue((prevValue) => {
        const nextValue =
          typeof newValue === 'function'
            ? (newValue as (prev: T) => T)(prevValue)
            : newValue

        return deepEqual(nextValue, prevValue) ? prevValue : nextValue
      })
    },
    [setValue]
  )

  return [value, customSetValue]
}
Example #6
Source File: useStateWithLocalStorage.ts    From taskcafe with MIT License 6 votes vote down vote up
useStateWithLocalStorage = (localStorageKey: string): [string, React.Dispatch<React.SetStateAction<string>>] => {
  const [value, setValue] = React.useState<string>(localStorage.getItem(localStorageKey) || '');

  React.useEffect(() => {
    localStorage.setItem(localStorageKey, value);
  }, [value]);

  return [value, setValue];
}
Example #7
Source File: Authorize.tsx    From gonear-name with The Unlicense 6 votes vote down vote up
Authorize = ({ near, setNear }: { near: INearProps | null, setNear: Dispatch<INearProps | null> }) => {
  const toProfile = useToProfile()
  
  if (!near) return null;

  const { api, signedIn, signedAccountId } = near
  
  const handleSignIn = async () => {
    api.signIn()
  }

  const handleSignOut = async () => {
    api.signOut()
    setNear({
      ...near,
      signedIn: false, 
      signedAccountId: null
    })
  }

  if (signedIn) {
    return (
      <Auth open={false}>
        <UserName onClick={toProfile}>{signedAccountId}</UserName>
        <LogOut onClick={handleSignOut} />
      </Auth>
    )
  }

  return (
    <Auth open={false}>
      <UserName onClick={handleSignIn}>Sign In</UserName>
    </Auth>
  )

}
Example #8
Source File: context.tsx    From hypertext with GNU General Public License v3.0 6 votes vote down vote up
function useLocalStorage<T, S = T>(
  key: LocalStorageKeys,
  defaultValue: T,
  overrideLookup = false,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  { serialize, deserialize }: { serialize: (toSerialize: T) => S; deserialize: (toDeserialize: S) => T } = {
    serialize: (toSerialize): S => (toSerialize as unknown) as S,
    deserialize: (toDeserialize): T => (toDeserialize as unknown) as T,
  }
): [T, Dispatch<SetStateAction<T>>] {
  const [value, setValue] = useState<T>(() => {
    if (overrideLookup) {
      return defaultValue
    } else {
      try {
        const item = window.localStorage.getItem(key)
        return item === null ? defaultValue : deserialize(JSON.parse(item)) ?? defaultValue
      } catch {
        return defaultValue
      }
    }
  })

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(serialize(value)))
    } catch {}
  }, [key, serialize, value])

  return [value, setValue]
}
Example #9
Source File: index.tsx    From chartsy with GNU General Public License v3.0 6 votes vote down vote up
TitlesContext = createContext<{
  titles: Title[];
  setTitles: Dispatch<SetStateAction<Title[]>>;
  lastUsed: number;
  setLastUsed: Dispatch<SetStateAction<number>>;
}>({
  titles: [...TitlesDefault],
  setTitles: () => null,
  lastUsed: 0,
  setLastUsed: () => null,
})
Example #10
Source File: useLocalStorage.tsx    From Tachidesk-WebUI with Mozilla Public License 2.0 6 votes vote down vote up
// eslint-disable-next-line max-len
export default function useLocalStorage<T>(
    key: string,
    defaultValue: T | (() => T),
): [T, Dispatch<SetStateAction<T>>] {
    const initialState = defaultValue instanceof Function ? defaultValue() : defaultValue;
    const [storedValue, setStoredValue] = useState<T>(
        storage.getItem(key, initialState),
    );

    const setValue = useCallback<React.Dispatch<React.SetStateAction<T>>>(
        ((value) => {
            setStoredValue((prevValue) => {
                // Allow value to be a function so we have same API as useState
                const valueToStore = value instanceof Function ? value(prevValue) : value;
                storage.setItem(key, valueToStore);
                return valueToStore;
            });
        }), [key],
    );

    return [storedValue, setValue];
}
Example #11
Source File: subscribeToNewBlock.ts    From useDApp with MIT License 6 votes vote down vote up
export function subscribeToNewBlock(
  provider: providers.BaseProvider | undefined,
  chainId: ChainId | undefined,
  dispatch: Dispatch<BlockNumberChanged>,
  isActive: boolean
) {
  if (provider && chainId !== undefined && isActive) {
    const update = (blockNumber: number) => dispatch({ chainId, blockNumber })
    provider.on('block', update)

    provider.getBlockNumber().then(
      (blockNumber) => update(blockNumber),
      (err) => {
        console.error(err)
      }
    )

    return () => {
      provider.off('block', update)
    }
  }

  return () => undefined
}
Example #12
Source File: AppCtx.tsx    From hub with Apache License 2.0 6 votes vote down vote up
export async function refreshUserProfile(dispatch: Dispatch<any>, redirectUrl?: string) {
  try {
    const profile: Profile = await API.getUserProfile();
    dispatch({ type: 'signIn', profile });
    const currentUrl = `${window.location.pathname}${
      window.location.search !== '' ? `?${cleanLoginUrlParams(window.location.search)}` : ''
    }`;
    if (!isUndefined(redirectUrl)) {
      if (redirectUrl === currentUrl) {
        history.replace(redirectUrl);
      } else {
        // Redirect to correct route when necessary
        history.push(redirectUrl);
      }
    }
  } catch (err: any) {
    dispatch({ type: 'signOut' });
    if (err.message === 'invalid session') {
      history.push(
        `${window.location.pathname}${
          window.location.search === '' ? '?' : `${window.location.search}&`
        }modal=login&redirect=${encodeURIComponent(`${window.location.pathname}${window.location.search}`)}`
      );
    }
  }
}
Example #13
Source File: useCurrency.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
export function useCurrency(): [Currency, Dispatch<SetStateAction<Currency>>] {
  const context = useContext(CurrencyContext);

  if (!context) {
    assertNever();
  }

  return [context.currency, context.setCurrency];
}
Example #14
Source File: useShallowState.ts    From fe-foundation with Apache License 2.0 6 votes vote down vote up
export function useShallowState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>] {

    const [state, setState] = useState<S>(initialState);

    const setShallowState = useCallback((action: SetStateAction<S>) => {

        setState(prevState => {

            let value: S;

            if (typeof action === 'function') {
                value = (action as (prevState: S) => S)(prevState);
            } else {
                value = action;
            }

            return shallowEqual(prevState, value) ? prevState : value;
        });
    }, []);

    return [state, setShallowState];
}
Example #15
Source File: useDisabledTest.tsx    From react-celo with MIT License 6 votes vote down vote up
useDisabledTest = (): [
  boolean,
  Dispatch<SetStateAction<boolean>>
] => {
  const { address } = useCelo();
  const [disabled, setDisabled] = useState(true);
  useEffect(() => {
    setDisabled(!address);
  }, [address]);

  return [disabled, setDisabled];
}
Example #16
Source File: actions.ts    From react-native-tiktok-clone with MIT License 6 votes vote down vote up
fetchFeeds = (feedType: FeedTypes) =>
  (dispatch: Dispatch<FeedActionTypes>) => {
    if (store.getState().feed.activeFeedType == feedType) return;
    dispatch(requestFeeds(feedType));
    firebase.firestore().collection(<string>feedType).get().then((doc: any) => {
      let feeds: Feed[] = [];
      doc.forEach((doc: any) => {
        let feed: Feed = <Feed>doc.data();
        feed.id = doc.id;
        feeds.push(feed);
      });
      dispatch(receiveFeeds(feeds));
    });
  }
Example #17
Source File: react-helpers.ts    From project-loved-web with MIT License 6 votes vote down vote up
export function setProperty<T, K extends keyof T>(
  setter: Dispatch<SetStateAction<T>>,
  property: K,
  value: T[K],
) {
  setter((prevState) => {
    return {
      ...prevState,
      [property]: value,
    };
  });
}
Example #18
Source File: useEditTestimony.ts    From advocacy-maps with MIT License 6 votes vote down vote up
function useTestimony(
  { uid, billId, draftRef, publicationRef }: State,
  dispatch: Dispatch<Action>
) {
  useEffect(() => {
    resolveBillTestimony(uid, billId)
      .then(({ draft, publication }) => {
        dispatch({ type: "resolveDraft", id: draft?.id })
        dispatch({ type: "resolvePublication", id: publication?.id })
      })
      .catch(error => dispatch({ type: "error", error }))
  }, [billId, dispatch, uid])

  useEffect(() => {
    if (draftRef)
      return onSnapshot(draftRef, {
        next: snap =>
          snap.exists() &&
          dispatch({ type: "loadDraft", value: snap.data() as DraftTestimony }),
        error: error => dispatch({ type: "error", error })
      })
  }, [dispatch, draftRef])

  useEffect(() => {
    if (publicationRef)
      return onSnapshot(publicationRef, {
        next: snap =>
          snap.exists() &&
          dispatch({
            type: "loadPublication",
            value: snap.data() as Testimony
          }),
        error: error => dispatch({ type: "error", error })
      })
  }, [dispatch, publicationRef])
}
Example #19
Source File: useStateFromProp.ts    From r3f-game-demo with MIT License 6 votes vote down vote up
export default function useStateFromProp<T = undefined>(
    prop: T
): [T, Dispatch<SetStateAction<T>>] {
    const [state, setState] = useState<T>(prop);
    const initial = useRef(true);

    useEffect(() => {
        if (!initial.current) {
            setState(prop);
        }
        initial.current = false;
    }, [prop]);

    return [state, setState];
}
Example #20
Source File: context.tsx    From homebase-app with MIT License 6 votes vote down vote up
CreatorContext = createContext<{
  state: CreatorState;
  dispatch: Dispatch<CreatorAction>;
  updateCache: (value: MigrationParams) => void;
}>({
  state: INITIAL_STATE,
  dispatch: () => null,
  updateCache: () => null,
})
Example #21
Source File: GameLandingPageComponents.tsx    From client with GNU General Public License v3.0 6 votes vote down vote up
export function TerminalToggler({
  terminalEnabled,
  setTerminalEnabled,
}: {
  terminalEnabled: boolean;
  setTerminalEnabled: Dispatch<SetStateAction<boolean>>;
}) {
  const uiEmitter = UIEmitter.getInstance();
  useLayoutEffect(() => {
    uiEmitter.emit(UIEmitterEvent.UIChange);
  }, [terminalEnabled, uiEmitter]);

  return (
    <StyledTerminalToggler
      terminalEnabled={terminalEnabled}
      onClick={() => setTerminalEnabled((b: boolean): boolean => !b)}
    >
      <span>{terminalEnabled ? '>' : '<'}</span>
    </StyledTerminalToggler>
  );
}
Example #22
Source File: HustlerConfig.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
randomizeHustlerAttributes = (
  dopeId: string,
  setHustlerConfig: Dispatch<SetStateAction<HustlerCustomization>>,
) => {
  const randomHustler = getRandomHustler({});
  setHustlerConfig({
    ...randomHustler,
    dopeId,
  });
}
Example #23
Source File: hooks.ts    From graphite-shot with MIT License 6 votes vote down vote up
usePastedImage = (): [
	string | undefined,
	Dispatch<SetStateAction<string | undefined>>
] => {
	const [imageData, setImageData] = useState<string>();
	useEffect(() => {
		const listener = (e: Event) => {
			const {clipboardData: data} = e as ClipboardEvent;
			const items = data?.items || [];

			for (let item of items) {
				if (item.type.indexOf("image") === -1) continue;
				const blob = item.getAsFile();
				let URLObj = window.URL || window.webkitURL;
				setImageData(URLObj.createObjectURL(blob));
				return;
			}
		};

		window.addEventListener("paste", listener);
		return () => window.removeEventListener("paste", listener);
	}, []);

	return [imageData, setImageData];
}
Example #24
Source File: useRefState.ts    From yugong with MIT License 6 votes vote down vote up
function useRefState<S>(
    initialState: S
): [S, Dispatch<SetStateAction<S>>, Readonly<MutableRefObject<S>>] {
    const refState = useRef<S>(initialState);
    const [state, setState] = useState<S>(initialState);
    const updater = useCallback((value: SetStateAction<S>) => {
        const nextState =
            typeof value === 'function'
                ? (value as (v: S) => S)(refState.current)
                : value;
        refState.current = nextState;
        setState(nextState);
    }, []);

    return [state, updater, refState];
}
Example #25
Source File: actions.ts    From frontend with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieved the currently logged in user's data. On error the state of
 * current data is assumed to be unchanged.
 * @param dispatch Reducer dispatch function used to update user context
 */
export async function getUserData(dispatch: Dispatch<UserStateAction>) {
  // Indicate the user data is being fetched
  dispatch({ type: 'loading' })

  // On network error just assume user state is unchanged
  let res: Response
  try {
    // Gets data for user with current session cookie
    res = await fetch(USER_INFO_URL, { credentials: 'include' })
  } catch {
    dispatch({ type: 'interrupt' })
    return
  }

  // Assuming a bad status indicates unchanged user state
  if (res.ok) {
    const info = await res.json()
    dispatch({
      type: 'login',
      info
    })
  } else {
    // 403 specifically indicates not currently logged in
    dispatch({ type: res.status === 403 ? 'logout' : 'interrupt' })
  }
}
Example #26
Source File: index.ts    From vite-ssr with MIT License 6 votes vote down vote up
export function useFetch<T = any>(url: string) {
  const { initialState } = useContext()

  const [state, setState] = useState(initialState[url])

  if (!state && !isLoading[url]) {
    isLoading[url] = true
    throw fetch(url)
      .then((result) => result.json())
      .then((result) => {
        isLoading[url] = false
        setState((initialState[url] = result))
      })
  }

  return [state, setState] as [T, Dispatch<T>]
}
Example #27
Source File: profile.tsx    From yasd with MIT License 6 votes vote down vote up
useProfileDispatch = (): Dispatch<ReducerAction> => {
  const context = React.useContext(ProfileDispatchContext)

  if (!context) {
    throw new Error()
  }

  return context
}
Example #28
Source File: use-input.tsx    From geist-ui with MIT License 6 votes vote down vote up
useInput = (
  initialValue: string,
): {
  state: string
  setState: Dispatch<SetStateAction<string>>
  currentRef: MutableRefObject<string>
  reset: () => void
  bindings: {
    value: string
    onChange: (event: BindingsChangeTarget) => void
  }
} => {
  const [state, setState, currentRef] = useCurrentState<string>(initialValue)

  return {
    state,
    setState,
    currentRef,
    reset: () => setState(initialValue),
    bindings: {
      value: state,
      onChange: (event: BindingsChangeTarget) => {
        if (typeof event === 'object' && event.target) {
          setState(event.target.value)
        } else {
          setState(event as string)
        }
      },
    },
  }
}
Example #29
Source File: terraform-plan.tsx    From terraform-visual with MIT License 6 votes vote down vote up
TerraofmrPlanProvider = ({ children }: any) => {
  const [state, Dispatch] = useReducer(reducer, {})

  return (
    <TerraformPlanDispatchContext.Provider value={Dispatch}>
      <TerraformPlanContext.Provider value={state}>{children}</TerraformPlanContext.Provider>
    </TerraformPlanDispatchContext.Provider>
  )
}