Skip to content
This repository has been archived by the owner on Jun 24, 2024. It is now read-only.

Commit

Permalink
Use defaultValue when there is no Provider
Browse files Browse the repository at this point in the history
  • Loading branch information
littensy committed Sep 1, 2021
1 parent df4e74f commit b0de98c
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/hooks/use-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ import { useState } from "./use-state";
import Roact from "@rbxts/roact";
import type { Destructor, RoactContext } from "../index";

interface RoactContextInternal<T> extends RoactContext<T> {
interface RoactContextInternal<T> {
Provider: Roact.ComponentConstructor<{
value: T;
}>;
Consumer: ConsumerConstructor<T>;
defaultValue: T;
}

interface ConsumerConstructor<T>
Expand Down Expand Up @@ -46,8 +50,11 @@ export function useContext<T>(context: RoactContext<T>): T {
return consumer.contextEntry;
});

const [value, setValue] = useState(contextEntry.value);
useEffect(() => contextEntry.onUpdate.subscribe(setValue), []);

return value;
if (contextEntry) {
const [value, setValue] = useState(contextEntry.value);
useEffect(() => contextEntry.onUpdate.subscribe(setValue), []);
return value;
} else {
return thisContext.defaultValue;
}
}

0 comments on commit b0de98c

Please sign in to comment.