I am new to react and am trying to understand why I'm seeing this error:
Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>
App.js
export default function App() {
const selectedNumber = useSelector(selectChosenNumber) // This line causes the error
function pickedNumberHandler() {
console.log("called")
}
let screen = <StartGameScreen />;
pickedNumberHandler()
store.subscribe(pickedNumberHandler)
return (
<Provider store={store}>
<LinearGradient colors={['#4e0329', '#ddb52f']} style={styles.rootScreen}>
<ImageBackground
source={require('./assets/images/background.png')}
resizeMode="cover"
style={styles.rootScreen}
imageStyle={{opacity: 0.15}}
>
{screen}
</ImageBackground>
</LinearGradient>
</Provider>
);
}
const styles = StyleSheet.create({
rootScreen: {
flex: 1,
}
})
chosenNumberReducer.ts
export const chosenNumberSlice = createSlice({
name: "chosenNumber",
initialState: {
value: ""
},
reducers: {
pickNumber: (state, action) => {
state.value = action.payload
}
}
})
export const { pickNumber } = chosenNumberSlice.actions
export const selectChosenNumber = state => state.chosenNumber.value;
export default chosenNumberSlice.reducer
I'm trying to listen to changes in state but can't seem to access the values in app.js.
You need to move your logic outside of App. When it says please ensure the component is wrapped in a <Provider>
it means that the component you are using the useSelector
in, needs to be under <Provider>
which in this case means App.js.
So App.js should contain only
export default function App() {
return (
<Provider store={store}>
<NewComponent .../>
</Provider>
);
}
And NewComponent.js should contain rest of the logic.