Joe B.
Joe B.

Reputation: 820

How to access state from multiple contexts in react native?

I'm using the context API to share state across many components in my application. I have a couple of different context files that I wrap as providers around my root level component. I'm curious how to use multiple context hooks within the same functional component. See below:

import { Context as EpisodeContext } from "../context/EpisodeContext";
import { Context as PlaybackContext } from "../context/PlaybackContext";

const EpisodeDetailsScreen = ({ navigation }) => {
  const { state } = useContext(PlaybackContext);
  const { state } = useContext(EpisodeContext)

....omitted for brevity.....
}

This code obviously doesn't work when I destructure the second state variable it is already defined above.

What is the proper way to do this?

Upvotes: 0

Views: 475

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53934

You just got name collision, its not related to React, try renaming one of the variables:

const { state } = useContext(PlaybackContext);
const { state: state2 } = useContext(EpisodeContext) // use state2 now

Upvotes: 1

Related Questions