Use Multiple React Context Providers in the Same App

Share this video with your friends

Send Tweet

When you have two unrelated kinds of data such as a current user and a currently-selected email, it’s common for some parts of the app to need the user and some other parts of the app to need the email. One way to do this is to create multiple Contexts, each with its own Provider and Consumer, and use each one to distribute one kind of data to the slices of the app that need it. In this lesson we’ll pass user data and email data to separate subtrees using two separate Contexts.

Felix
Felix
~ 6 years ago

Hi, could you provide some example code for api.js? Would this be a class component with global fetch/axios config and then named exports for each API endpoint? Thanks

Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

api.js is included in the example code for the lesson. It's not a component, just a set of named exports, one for each endpoint. Like export function login(username, password) { ... }. The file for this example has some fake data setup and stuff, but in a real app, it'd have the global fetch or axios config like you mention.

Steve
Steve
~ 6 years ago

I forked your sandbox and now I seem to be getting: Error A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://fb.me/react-crossorigin-error for more information. ▶ 17 stack frames were collapsed. evaluate /src/index.js:17:9 14 | ); 15 | } 16 |

17 | ReactDOM.render( | ^ 18 | <UserProvider> 19 | <EmailProvider> 20 | <Root />

Can you help? I'm stuck now.

Steve
Steve
~ 6 years ago

Nevermind! I found the typo!

Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

FYI: The 'before' code for this lesson is here if you need it.

shiraz samad
shiraz samad
~ 6 years ago

I have an AuthContext which sets the autentication token on componentDidMount(). Also a nested component which fetches data once the api authentication is done. but right now the fetchData() method is getting executed before getting the authToken. This cause the fetchData() request call to fail. Is there a way to make sure my AuthContext runs before the rest of the nested context getting triggered.

Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

@shiraz React renders the children before the parents, because a component isn't considered "mounted" until all of its nested children have been rendered. I'd suggest checking that the authToken is present before making the call in fetchData, and rely on the fact that the nested component will re-render after the AuthContext has updated its state with the token.

shiraz samad
shiraz samad
~ 6 years ago

Thanks @Dave