1

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.

1
  • You Should use Provider in Upper level component (i.e. Index.js). After that, you can use useSelector in this component. Commented May 27, 2022 at 15:15

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.