Skip to content

Commit 2c6d3bc

Browse files
committed
fix: default Context value
1 parent a638ca4 commit 2c6d3bc

2 files changed

Lines changed: 19 additions & 7 deletions

File tree

src/context.tsx

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,13 @@ export interface ContextSelectorProviderProps<T> {
2525
export interface SelectorContext<ContextProps> {
2626
Context: React.Context<Context<ContextProps>>;
2727
Provider: React.ComponentType<ContextSelectorProviderProps<ContextProps>>;
28+
defaultValue?: ContextProps;
2829
}
2930

3031
export function createContext<ContextProps>(
31-
defaultContext?: ContextProps,
32+
defaultValue?: ContextProps,
3233
): SelectorContext<ContextProps> {
33-
const Context = React.createContext<Context<ContextProps>>(defaultContext as any);
34+
const Context = React.createContext<Context<ContextProps>>(undefined);
3435

3536
const Provider = ({ value, children }: ContextSelectorProviderProps<ContextProps>) => {
3637
const valueRef = React.useRef(value);
@@ -52,13 +53,11 @@ export function createContext<ContextProps>(
5253
return <Context.Provider value={context}>{children}</Context.Provider>;
5354
};
5455

55-
return { Context, Provider };
56+
return { Context, Provider, defaultValue };
5657
}
5758

5859
/** e.g. useSelect(userContext) => user */
59-
export function useContext<ContextProps>(
60-
holder: SelectorContext<ContextProps>,
61-
): ContextProps;
60+
export function useContext<ContextProps>(holder: SelectorContext<ContextProps>): ContextProps;
6261

6362
/** e.g. useSelect(userContext, user => user.name) => user.name */
6463
export function useContext<ContextProps, SelectorValue>(
@@ -105,7 +104,7 @@ export function useContext<ContextProps, SelectorValue>(
105104
const { listeners, getValue } = context || {};
106105

107106
const valueRef = React.useRef<SelectorValue>();
108-
valueRef.current = eventSelector(context ? getValue() : null);
107+
valueRef.current = eventSelector(context ? getValue() : holder?.defaultValue);
109108
const [, forceUpdate] = React.useState({});
110109

111110
useLayoutEffect(() => {

tests/context.test.tsx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,4 +185,17 @@ describe('Basic', () => {
185185
expect(container.querySelector('#times')!.textContent).toEqual('2');
186186
expect(container.querySelector('#value')!.textContent).toEqual('light');
187187
});
188+
189+
it('defaultValue', () => {
190+
const DefaultContext = createContext('little');
191+
const Demo = () => (
192+
<>
193+
<Value id="value" value={useContext(DefaultContext)} />
194+
</>
195+
);
196+
197+
const { container } = render(<Demo />);
198+
199+
expect(container.querySelector('#value')!.textContent).toEqual('little');
200+
});
188201
});

0 commit comments

Comments
 (0)