I have the following useContext definitions in my types.ts file:
type Score = {
correct: number;
incorrect: number;
};
export type ReactQuizContextType = {
check: SharedValue<string>;
activeIndex: SharedValue<number>;
direction: SharedValue<string>;
redo: boolean;
setRedo: React.Dispatch<React.SetStateAction<boolean>>;
score: Score;
setScore: React.Dispatch<
React.SetStateAction<{
correct: number;
incorrect: number;
}>
>;
};
export const ReactQuizContext = React.createContext<ReactQuizContextType>({
check: useSharedValue("wrong"),
activeIndex: useSharedValue(0),
direction: useSharedValue("vertical"),
redo: false,
setRedo: () => {},
score: {
correct: 0,
incorrect: 0,
},
setScore: () => {},
});
export const useReactQuizContext = () => React.useContext(ReactQuizContext);
What I’d like to do is simply wrap my ReactQuiz component with the corresponding provider:
return (
<ReactQuizContext.Provider
value={{ score, setScore, redo, setRedo, activeIndex, direction, check }}
>
<GestureHandlerRootView style={styles.container}>
<StatusBar style="auto" hidden />
{/* <ReactLogo route={route} navigation={navigation} /> */}
<GestureDetector gesture={Gesture.Exclusive(flingUp, flingDown)}>
<View style={[styles.dataContainer]} pointerEvents="box-none">
{data.map((item, index) => (
// <Card
// info={item}
// key={item.id}
// index={index}
// activeIndex={activeIndex}
// totalLength={data.length - 1}
// direction={direction}
// onCorrect={onCorrect}
// onIncorrect={onIncorrect}
// />
<Text>Hi</Text>
))}
</View>
</GestureDetector>
</GestureHandlerRootView>
</ReactQuizContext.Provider>
)
I’ve narrowed it down to the provider definitely being the cause of the issue and I’ve always worked with redux so I’m rusty with useContext.
I’m getting the invalid hook call error, the classic and not sure how to fix
>Solution :
export const ReactQuizContext = React.createContext<ReactQuizContextType>({
check: useSharedValue("wrong"),
activeIndex: useSharedValue(0),
direction: useSharedValue("vertical"),
redo: false,
setRedo: () => {},
score: {
correct: 0,
incorrect: 0,
},
setScore: () => {},
});
You are calling useSharedValue three times here, but this is code outside of a component. These lines are defining the default of the context (ie, the value if no ReactQuizContext.Provider is found), so you just need to provide constants:
export const ReactQuizContext = React.createContext<ReactQuizContextType>({
check: { value: "wrong" },
activeIndex: { value: 0 },
direction: { value: "vertical" },
redo: false,
setRedo: () => {},
score: {
correct: 0,
incorrect: 0,
},
setScore: () => {},
});
Feel free to call useSharedValue in the provider component to create the real value