react#SetStateAction TypeScript Examples

The following examples show how to use react#SetStateAction. 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: 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 #3
Source File: useLocalStorage.ts    From TabMerger with GNU General Public License v3.0 6 votes vote down vote up
export default function useLocalStorage<T>(key: string, initialValue: T): [T, Dispatch<SetStateAction<T>>] {
  const [storedValue, setStoredValue] = useState<T>(initialValue);

  const setValue: Dispatch<SetStateAction<T>> = useCallback(
    (value) => {
      chrome.storage.local.set({ [key]: value }, () => {
        setStoredValue(value);
      });
    },
    [key]
  );

  useEffect(() => {
    chrome.storage.local.get([key], (value) => {
      setValue(value[key] ?? initialValue);
    });
  }, [key, initialValue, setValue]);

  const handleStorageChange = useCallback(
    (changes: { [key: string]: chrome.storage.StorageChange }, areaName: chrome.storage.AreaName) => {
      if (areaName === "local" && changes[key]) {
        setStoredValue(changes[key].newValue);
      }
    },
    [key]
  );

  useEffect(() => {
    chrome.storage.onChanged.addListener(handleStorageChange);

    return () => chrome.storage.onChanged.removeListener(handleStorageChange);
  }, [handleStorageChange]);

  return [storedValue, setValue];
}
Example #4
Source File: usePersistentState.ts    From jitsu with MIT License 6 votes vote down vote up
/**
 * Same as useState, but persist state in local storage
 */
export function usePersistentState<S>(initialState: S | (() => S), localKey: string): [S, Dispatch<SetStateAction<S>>] {
  const local = localStorage.getItem(localKey)
  const [state, setState] = useState(local === null ? initialState : JSON.parse(local))
  return [
    state,
    newState => {
      localStorage.setItem(localKey, JSON.stringify(newState))
      setState(newState)
    },
  ]
}
Example #5
Source File: usePersistentState.ts    From iplocate with MIT License 6 votes vote down vote up
usePersistentState = <T>(
  key: string,
  defaultValue: any = undefined
): [T, React.Dispatch<SetStateAction<T>>] => {
  const [value, setValue] = useState<T>(() => {
    const existing = localStorage.getItem(key);
    if (existing) {
      return JSON.parse(existing);
    }
    return defaultValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [value, key]);

  return [value, setValue];
}
Example #6
Source File: use-tabs.ts    From geist-ui with MIT License 6 votes vote down vote up
useTabs = (
  initialValue: string,
): {
  state: string
  setState: Dispatch<SetStateAction<string>>
  currentRef: MutableRefObject<string>
  bindings: {
    value: string
    onChange: (val: string) => void
  }
} => {
  const [state, setState, currentRef] = useCurrentState<string>(initialValue)

  return {
    state,
    setState,
    currentRef,
    bindings: {
      value: state,
      onChange: (val: string) => {
        setState(val)
      },
    },
  }
}
Example #7
Source File: useStorageWithSave.ts    From TabMerger with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This is a wrapper for using local storage in scenarios where it is needed to also
 * be able to cancel/save based on some local state
 * @note In most cases the first element that is returned is not needed, but is provided for convenience
 */
export default function useStorageWithSave<T>(
  key: string,
  initialValue: T
): [T, Dispatch<SetStateAction<T>>, T, Dispatch<SetStateAction<T>>] {
  const [value, setValue] = useLocalStorage(key, initialValue);

  const [localValue, setLocalValue] = useState(initialValue);

  useEffect(() => setLocalValue(value), [value]);

  return [value, setValue, localValue, setLocalValue];
}
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: usePersistentState.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
usePersistentState = <T extends any = any>(
  key: string,
  defaultValue?: any
): [T, React.Dispatch<SetStateAction<T>>] => {
  const cookies = useMemo(() => new Cookies(), []);

  const [state, setState] = useState<T>(() => {
    const existing = localStorage.getItem(key);
    try {
      return existing ? JSON.parse(existing) : defaultValue;
    } catch {
      return defaultValue;
    }
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(state));
    if (key === 'token') {
      cookies.set('crossfeed-token', state, {
        domain: process.env.REACT_APP_COOKIE_DOMAIN
      });
    }
  }, [state, key, cookies]);

  return [state, setState];
}
Example #14
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 #15
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 #16
Source File: TextField.tsx    From Demae with MIT License 6 votes vote down vote up
useTextField = (initValue?: string, props: TextFieldProps = {}): [TextFieldProps, Dispatch<SetStateAction<string>>] => {
	const [value, setValue] = useState<string>(initValue || "")
	const [error, setError] = useState(false)

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

	const onChange = props.onChange || ((e) => {
		const value = e.target.value
		setValue(value)
		if (props.inputProps && value) {
			const pattern = props.inputProps["pattern"]
			const regex = new RegExp(pattern)
			setError(!value.match(regex))
		}
	})

	const onBlur = props.onBlur || ((e) => {
		const value = e.target.value
		if (props.inputProps && value) {
			const pattern = props.inputProps["pattern"]
			const regex = new RegExp(pattern)
			setError(!value.match(regex))
		}
	})

	return [{ value, error, onChange, onBlur, ...props } as TextFieldProps, setValue]
}
Example #17
Source File: mentionHelper.ts    From lexicon with MIT License 6 votes vote down vote up
export function mentionHelper(
  text: string,
  cursorPosition: CursorPosition,
  setShowUserList: (value: SetStateAction<boolean>) => void,
  setMentionLoading: (value: SetStateAction<boolean>) => void,
  setMentionKeyword: (value: SetStateAction<string>) => void,
) {
  if (text.charAt(cursorPosition.end - 2) === '@') {
    setShowUserList(true);
  }

  if (text.charAt(cursorPosition.end - 2) === ' ' || !text.includes('@')) {
    setShowUserList(false);
  }

  let keywords = text.match(/@[A-Za-z0-9._-]*$/);
  setMentionKeyword(keywords ? keywords[0].substr(1) : '');

  if (keywords && keywords[0].substr(1).length > 0) {
    setMentionLoading(true);
  }
}
Example #18
Source File: discount-form-context.tsx    From admin with MIT License 6 votes vote down vote up
DiscountFormContext = React.createContext<{
  type?: string
  isDynamic: boolean
  hasExpiryDate: boolean
  setHasExpiryDate: (value: boolean) => void
  hasStartDate: boolean
  setHasStartDate: (value: boolean) => void
  handleConfigurationChanged: (values: string[]) => void
  conditions: ConditionMap
  updateCondition: (props: UpdateConditionProps) => void
  setConditions: Dispatch<SetStateAction<ConditionMap>>
  handleReset: () => void
} | null>(null)
Example #19
Source File: useRafState.ts    From tailchat with GNU General Public License v3.0 6 votes vote down vote up
useRafState = <S>(
  initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>] => {
  const frame = useRef(0);
  const [state, setState] = useState(initialState);

  const setRafState = useCallback((value: S | ((prevState: S) => S)) => {
    cancelAnimationFrame(frame.current);

    frame.current = requestAnimationFrame(() => {
      setState(value);
    });
  }, []);

  useUnmount(() => {
    cancelAnimationFrame(frame.current);
  });

  return [state, setRafState];
}
Example #20
Source File: TabsOfTruth.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
createTabsContext = (tabs: Tab[], defaultActiveTabIndex = 0) => {
  const context = createContext<[State, Dispatch<SetStateAction<number>>]>([{ tabs, activeTabIndex: defaultActiveTabIndex }] as never)

  const TabsOfTruthProvider: FC = ({ children }) => {
    const [activeTabIndex, setActiveTabIndex] = useState<number>(defaultActiveTabIndex)
    return providerFactory(
      context,
      {
        value: useMemo<[State, Dispatch<SetStateAction<number>>]>(
          () => [{ activeTabIndex, tabs: tabs.map((t, index) => ({ ...t, active: index === activeTabIndex })) }, setActiveTabIndex],
          [activeTabIndex],
        ),
      },
      children,
    )
  }

  return [createUseContextFn(context), TabsOfTruthProvider, context] as const
}
Example #21
Source File: useStateSafely.ts    From assisted-ui-lib with Apache License 2.0 6 votes vote down vote up
useStateSafely = <S>(initialState: S): [S, Dispatch<SetStateAction<S>>] => {
  const mountedRef = useRef(false);
  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);

  const [state, setState] = useState(initialState);
  const setStateSafely: Dispatch<SetStateAction<S>> = useCallback((arg) => {
    if (mountedRef.current) {
      setState(arg);
    }
  }, []);

  return [state, setStateSafely];
}
Example #22
Source File: AppInfoModal.tsx    From DockerLocal with MIT License 6 votes vote down vote up
AppInfoModal: React.FC<{
  setShowModal: Dispatch<SetStateAction<boolean>>;
}> = ({ setShowModal }) => {
  return (
    <div className="modal is-active">
      <div className="modal-background"></div>
      <div className="modal-card">
        <header className="modal-card-head">
          <p className="modal-card-title">About DockerLocal</p>
          <button
            aria-label="close"
            className="button"
            onClick={(): void => setShowModal(false)}
          >
            x
          </button>
        </header>
        <section className="modal-card-body">{AppInfoList}</section>
        <section className="modal-card-body">
          To get started, please create a personal access token from on your github account. Instructions are on our github readme.
        </section>
        <footer className="modal-card-foot">
          <button className="button" onClick={(): void => setShowModal(false)}>
            Close
          </button>
        </footer>
      </div>
    </div>
  );
}
Example #23
Source File: Inspector.tsx    From PMTiles with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
TileRow = (props: {
  entry: Entry;
  setSelectedEntry: Dispatch<SetStateAction<Entry | null>>;
}) => {
  return (
    <TableRow
      onClick={() => {
        props.setSelectedEntry(props.entry);
      }}
    >
      <td>{props.entry.z}</td>
      <td>{props.entry.x}</td>
      <td>{props.entry.y}</td>
      <td>{props.entry.offset}</td>
      <td>{props.entry.length}</td>
      <td>{props.entry.is_dir}</td>
    </TableRow>
  );
}
Example #24
Source File: useDebouncedState.ts    From web with MIT License 6 votes vote down vote up
/**
 * Like `useSafeState` but its state setter is debounced.
 *
 * @param initialState Initial state to pass to underlying `useSafeState`.
 * @param delay Debounce delay.
 * @param maxWait Maximum amount of milliseconds that function can be delayed
 * before it's force execution. 0 means no max wait.
 */
export function useDebouncedState<S>(
  initialState: S | (() => S),
  delay: number,
  maxWait = 0
): [S, Dispatch<SetStateAction<S>>] {
  const [state, setState] = useSafeState(initialState);

  return [state, useDebouncedCallback(setState, [], delay, maxWait)];
}
Example #25
Source File: DeleteAccount.tsx    From coindrop with GNU General Public License v3.0 6 votes vote down vote up
handleDelete = async (
    logout,
    setIsSubmitting: Dispatch<SetStateAction<boolean>>,
    user: User,
    setStatus: Dispatch<SetStateAction<Status>>,
) => {
    setIsSubmitting(true);
    try {
        await deleteUser(user);
        setStatus('success');
        const redirectDelay = 5000;
        setTimeout(logout, redirectDelay);
    } catch (err) {
        setStatus('error');
    } finally {
        setIsSubmitting(false);
    }
}
Example #26
Source File: useLocalStorage.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
export function useLocalStorage<T>(
  key: string,
  initialValue: T
): [T, Dispatch<SetStateAction<T>>, Dispatch<SetStateAction<void>>] {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = isWindow && window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  const setValue = (value: T) => {
    try {
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);

      isWindow &&
        window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(error);
    }
  };

  const removeValue = () => {
    try {
      setStoredValue(null);

      isWindow && window.localStorage.removeItem(key);
    } catch (error) {
      console.error(error);
    }
  };

  return [storedValue, setValue, removeValue];
}
Example #27
Source File: hooks.ts    From drip-table with MIT License 6 votes vote down vote up
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 #28
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 #29
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]
}