Reputation: 2638
I have use React Context API
hook in react native. I created Consumer
and Provider
both to pass props and state from parent to child. Code is working perfectly fine, I have received props from parent to child.
I have received following warning on my console:-
Warning: Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?
Please check below added code:-
I have create common context file CommonContext.js
.
import React, {createContext} from 'react';
const MyContext = createContext();
export const LoginProvider = MyContext.Provider;
export const LoginConsumer = MyContext.Consumer;
This is my provider code
import React, {PureComponent} from 'react';
import {View, Text} from 'react-native';
import {LoginProvider} from './CommonContext';
export default class Login extends PureComponent {
constructor(props) {
super(props);
}
render() {
return (
<View style={Styles.mainContainer}>
<LoginProvider value={this.props}>
<LoginScreenView />
</LoginProvider>
</View>
);
}
}
From this way i am access parent component data into child hook
import {LoginConsumer} from './CommonContext';
export default function LoginScreenView(props) {
let loginConsumer = useContext(LoginConsumer);
return (
<View style={Styles.mainContainer}>
<Text>{loginConsumer}</Text>
</View>
);
}
Upvotes: 1
Views: 7337
Reputation:
You are receiving this error because you are calling useContext
on a Context.Consumer
instance, instead of a Context
.
You do like this:
export const LoginConsumer = MyContext.Consumer;
and then you call useContext
on LoginConsumer
:
let loginConsumer = useContext(LoginConsumer);
Instead, you should call useContext
on MyContext
, like this:
CommonContext.js
:export const MyContext = createContext();
import { MyContext } from './CommonContext';
useContext
:let login = useContext(MyContext);
So your second component that you posted would look like this:
import { MyContext } from './CommonContext';
export default function LoginScreenView(props) {
let login = useContext(MyContext);
return (
<View style={Styles.mainContainer}>
<Text>{login}</Text>
</View>
);
}
Upvotes: 4