react#Context TypeScript Examples
The following examples show how to use
react#Context.
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: stores.tsx From calories-in with MIT License | 6 votes |
function makeUseContext<T>(context: Context<T>) {
function useCustomContext() {
const value = useContext(context)
if (!guard(value)) {
throw new Error('Missing store context provider')
}
return value
}
return useCustomContext
}
Example #2
Source File: QueryField.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
constructor(props: QueryFieldProps, context: Context<any>) {
super(props, context);
this.runOnChangeDebounced = _.debounce(this.runOnChange, 500);
const { onTypeahead, cleanText, portalOrigin, onWillApplySuggestion } = props;
// Base plugins
this.plugins = [
NewlinePlugin(),
SuggestionsPlugin({ onTypeahead, cleanText, portalOrigin, onWillApplySuggestion }),
ClearPlugin(),
RunnerPlugin({ handler: this.runOnChangeAndRunQuery }),
SelectionShortcutsPlugin(),
IndentationPlugin(),
ClipboardPlugin(),
...(props.additionalPlugins || []),
].filter(p => p);
this.state = {
suggestions: [],
typeaheadContext: null,
typeaheadPrefix: '',
typeaheadText: '',
value: makeValue(props.query || '', props.syntax),
};
}
Example #3
Source File: index.ts From mStable-apps with GNU Lesser General Public License v3.0 | 6 votes |
createUseContextFn =
<T>(context: Context<T>, checkNull?: boolean) =>
(): T => {
const value = useContext(context)
if (checkNull && value == null) {
throw new Error(`${context.displayName} must be used inside a ${context.Provider.name}.`)
}
return value
}
Example #4
Source File: VersionedContext.ts From backstage with Apache License 2.0 | 6 votes |
/**
* Get the existing or create a new versioned React context that's
* stored inside a global singleton.
*
* @param key - A key that uniquely identifies the context.
* @public
* @example
*
* ```ts
* const MyContext = createVersionedContext<{ 1: string }>('my-context');
*
* const MyContextProvider = ({children}) => (
* <MyContext.Provider value={createVersionedValueMap({ 1: 'value-for-version-1' })}>
* {children}
* <MyContext.Provider>
* )
* ```
*/
export function createVersionedContext<
Versions extends { [version in number]: unknown },
>(key: string): Context<VersionedValue<Versions> | undefined> {
return getOrCreateGlobalSingleton(key, () =>
createContext<VersionedValue<Versions> | undefined>(undefined),
);
}
Example #5
Source File: index.ts From mStable-apps with GNU Lesser General Public License v3.0 | 6 votes |
createToggleContext = (
defaultInitialValue = false,
): Readonly<[() => Toggle, FC<{ initialValue?: boolean }>, Context<Toggle>]> => {
const context = createContext<Toggle>(undefined as never)
const ToggleProvider: FC<{ initialValue?: boolean }> = ({ children, initialValue }) => {
const toggle = useToggle(initialValue !== undefined ? initialValue : defaultInitialValue)
return providerFactory(context, { value: toggle }, children)
}
return [createUseContextFn(context, true), ToggleProvider, context] as const
}
Example #6
Source File: createExchangeContext.ts From mStable-apps with GNU Lesser General Public License v3.0 | 6 votes |
createExchangeContext = (
defaultInitialValue = ExchangeAction.Default,
): Readonly<[() => State, FC<{ initialValue?: ExchangeAction }>, Context<State>]> => {
const context = createContext<State>(undefined as never)
const ExchangeProvider: FC<{ initialValue?: ExchangeAction }> = ({ children, initialValue }) => {
const state = useState(initialValue !== undefined ? initialValue : defaultInitialValue)
return providerFactory(context, { value: state }, children)
}
return [createUseContextFn(context, true), ExchangeProvider, context] as const
}
Example #7
Source File: RecordRoot.hook.ts From ke with MIT License | 6 votes |
export function useRecordRoot<K extends string | number, T>(
context: Context<RootContext>,
recRoot: Record<K, T>,
onChange: (updater: Updater<Record<K, T>>) => void
): RootProviderDesc<T> {
const setter = useCallback(
(key: string | number, updater: Updater<T>) =>
onChange((prev) => {
checkKeyInRecord(key, prev)
const updated = updater(prev[key as K])
return isEqual(prev[key as K], updated) ? prev : { ...prev, [key]: updated }
}),
[onChange]
)
const getter = useCallback(
(key: string | number): T => {
checkKeyInRecord(key, recRoot)
return recRoot[key as K]
},
[recRoot]
)
return [context.Provider as Provider<RootContext<T>>, { value: [getter, setter] }]
}
Example #8
Source File: react-helpers.ts From project-loved-web with MIT License | 6 votes |
export function useRequiredContext<T>(context: Context<T | undefined>): T {
const contextValue = useContext(context);
if (contextValue == null) {
throw new Error('Missing context provider');
}
return contextValue;
}
Example #9
Source File: VisibilityProvider.tsx From fivem-react-boilerplate-lua with MIT License | 5 votes |
useVisibility = () => useContext<VisibilityProviderValue>(VisibilityCtx as Context<VisibilityProviderValue>)
Example #10
Source File: Row.tsx From gio-design with Apache License 2.0 | 5 votes |
RowContext: Context<RowContextState> = createContext({ gutters: [0, 0] })
Example #11
Source File: createRewardsEarnedContext.ts From mStable-apps with GNU Lesser General Public License v3.0 | 5 votes |
createRewardsEarnedContext = (): Readonly<[() => RewardsEarned, FC, Context<RewardsEarned>]> => {
const context = createContext<RewardsEarned>(null as never)
const RewardEarnedProvider: FC = ({ children }) => {
const stakedTokenQuery = useStakedTokenQuery()
const stakedTokenData = stakedTokenQuery.data?.stakedToken
const stakedToken = useTokenSubscription(stakedTokenData?.id)
const stakedTokenBalance = stakedToken?.balance
const [value, setValue] = useState<RewardsEarned>({ rewards: 0 })
useInterval(() => {
if (!(stakedTokenBalance && stakedTokenData?.stakingRewards && stakedTokenData.accounts?.[0])) {
return setValue({ rewards: 0 })
}
const {
stakingRewards: { lastUpdateTime, periodFinish, rewardPerTokenStored: _rewardPerTokenStored, rewardRate },
token: {
totalSupply: { bigDecimal: totalTokens },
},
accounts: [{ rewards: _rewards, rewardPerTokenPaid }],
} = stakedTokenData
// TODO as @client Apollo fields
const rewardPerTokenStored = BigNumber.from(_rewardPerTokenStored)
const rewards = BigNumber.from(_rewards)
const rewardPerToken = (() => {
if (totalTokens.exact.eq(0)) {
// If there is no StakingToken liquidity, avoid div(0)
return rewardPerTokenStored
}
const lastTimeRewardApplicable = Math.min(periodFinish, getUnixTime(Date.now()))
const timeSinceLastUpdate = lastTimeRewardApplicable - lastUpdateTime
// New reward units to distribute = rewardRate * timeSinceLastUpdate
const rewardUnitsToDistribute = BigNumber.from(rewardRate).mul(timeSinceLastUpdate)
// New reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens
const unitsToDistributePerToken = rewardUnitsToDistribute.mul(SCALE).div(totalTokens.exact)
return rewardPerTokenStored.add(unitsToDistributePerToken)
})()
// Current rate per token - rate user previously received
const userRewardDelta = rewardPerToken.sub(rewardPerTokenPaid)
if (userRewardDelta.eq(0)) {
return { rewards: new BigDecimal(rewards).simple, canClaim: rewards.gt(0) }
}
// New reward = staked tokens * difference in rate
const userNewReward = stakedTokenBalance.mulTruncate(userRewardDelta)
// Add to previous rewards
const summedRewards = rewards.add(userNewReward.exact)
return setValue({
canClaim: summedRewards.gt(0),
rewards: new BigDecimal(summedRewards).simple,
})
}, 5e3)
return providerFactory(context, { value }, children)
}
return [createUseContextFn(context), RewardEarnedProvider, context] as const
}
Example #12
Source File: index.ts From mStable-apps with GNU Lesser General Public License v3.0 | 5 votes |
providerFactory = <T>(context: Context<T>, props: { value: T }, children: ReactNode): ReactElement =>
createElement(context.Provider, props, children)
Example #13
Source File: ConfigContext.ts From caple-design-system with MIT License | 5 votes |
ConfigContext: Context<ConfigContextState> = createContext({ prefix: config.prefix, })
Example #14
Source File: ContentStore.ts From Cleanarr with MIT License | 5 votes |
export function newContentStoreContext(): Context<ContentStore> {
return React.createContext<ContentStore>(newContentStore());
}
Example #15
Source File: MediaStore.ts From Cleanarr with MIT License | 5 votes |
export function newMediaStoreContext(): Context<MediaStore> {
return React.createContext<MediaStore>(newMediaStore());
}
Example #16
Source File: ServerInfoStore.ts From Cleanarr with MIT License | 5 votes |
export function newServerInfoStoreContext(): Context<ServerInfoStore> {
return React.createContext<ServerInfoStore>(newServerInfoStore());
}
Example #17
Source File: Context.tsx From UsTaxes with GNU Affero General Public License v3.0 | 5 votes |
formContainerContext: Context<FormContainerProps> = createContext( getProps() )
Example #18
Source File: stores.tsx From calories-in with MIT License | 5 votes |
function makeProvider<T>() {
const Context = createContext<T | undefined>(undefined)
const useContext = makeUseContext(Context)
return [Context.Provider, useContext] as const
}
Example #19
Source File: context.tsx From anchor-web-app with Apache License 2.0 | 5 votes |
AnchorWebappContext: Context<AnchorWebapp> =
// @ts-ignore
createContext<AnchorWebapp>()
Example #20
Source File: SwitchContext.tsx From caple-design-system with MIT License | 5 votes |
SwitchContext: Context<SwitchContextState> = createContext({})
Example #21
Source File: RadioContext.tsx From caple-design-system with MIT License | 5 votes |
RadioContext: Context<RadioContextState> = createContext({})
Example #22
Source File: NavigationContext.tsx From caple-design-system with MIT License | 5 votes |
NavigationContext: Context<NavigationContextState> = createContext({})
Example #23
Source File: RowContext.ts From caple-design-system with MIT License | 5 votes |
RowContext: Context<RowContextState> = createContext({})
Example #24
Source File: FloatingLabelSelectContext.tsx From caple-design-system with MIT License | 5 votes |
FloatingLabelSelectContext: Context<FloatingLabelSelectContextState> = createContext({})
Example #25
Source File: Leaf.hook.ts From ke with MIT License | 5 votes |
export function useLeaf(context: Context<RootContext>, key: string | number): [LeafData, (updater: Updater) => void] {
const [getKey, updateKey] = useContext(context)
const updateLeaf = useCallback((updater: Updater) => updateKey(key, updater), [key, updateKey])
return [getKey(key), updateLeaf]
}
Example #26
Source File: ArrayRoot.hook.ts From ke with MIT License | 5 votes |
export function useArrayRoot<T>(
context: Context<RootContext>,
arrRoot: T[],
onChange: (updater: Updater<T[]>) => void,
getKey: (value: T, index: number) => string | number
): RootProviderDesc<T> {
const setter = useCallback(
(key: number | string, updater: Updater<T>) =>
onChange((prev) => {
const updatedIndex = prev.findIndex((item, index) => key === getKey(item, index))
if (updatedIndex < 0) {
throw new RangeError(`Invalid key "${key}" for update Array Root. Available keys: ${prev.map(getKey)}`)
}
const updated = updater(prev[updatedIndex])
if (!isEqual(prev[updatedIndex], updated)) {
const updatedRoot = [...prev]
updatedRoot[updatedIndex] = updated
return updatedRoot
}
return prev
}),
[onChange, getKey]
)
const getter = useCallback(
(key: string | number): T => {
const getIndex = arrRoot.findIndex((item, index) => key === getKey(item, index))
if (getIndex < 0) {
throw new RangeError(`Invalid key "${key}" for Array Root. Available keys: ${arrRoot.map(getKey)}`)
}
return arrRoot[getIndex]
},
[arrRoot, getKey]
)
return [context.Provider as Provider<RootContext<T>>, { value: [getter, setter] }]
}
Example #27
Source File: visibility.tsx From mojito_pdm with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
useVisibility = () => useContext<VisibilityProviderValue>(VisibilityCtx as Context<VisibilityProviderValue>)
Example #28
Source File: Jobs.tsx From anchor-web-app with Apache License 2.0 | 5 votes |
JobsContext: Context<Jobs> = createContext<Jobs>()
Example #29
Source File: theme.tsx From anchor-web-app with Apache License 2.0 | 5 votes |
ThemeContext: Context<ThemeState> = createContext<ThemeState>()