Reputation: 784
I'm using react context api to show my data everywhere and updating from everywhere I want that my data can be show on multiple screens and I can update from more than one class I need to use that globally.
When I try to update it from class profile screens nothing happen but it can be updating from class home screen.
How Can I show my data in consumer without using like this ,and show this data globally
const Context = React.createContext("default value")
global.cart = 1;
Class home screen that is context provider class
class HomeScreen extends Component<Props> {
constructor(props){
super(props);
this.state={
contextData:5}}
render() {
return (
<View>
<Context.Provider value={this.state.contextData}>
<Button title="Increment" onPress={++global.cart;
this.setState({contextData:global.cart})}/>
</Context.Provider>
<ProfileScreens/>
</View>
)
}
}
text that I need to use and show in many screens
class ProfileScreen extends Component<Props> {
render() {
return (
<View style={{}}>
<Context.Consumer>
{data=> <Text style={{fontSize:50}}>{data.toString()}</Text>}
</Context.Consumer>
</View>
);
}
}
another class which is changing the context provider data
class ProfileScreens extends Component<Props> {
constructor(props){
super(props);
this.state={contextData:5}}
render() {
return (
<View >
<Context.Provider value={this.state.contextData}>
<ProfileScreen/>
<Button title="decrementss" onPress={()=>{ ++global.cart;
this.setState({contextData:global.cart})}}/>
</Context.Provider>
</View>
);
}
}
Upvotes: 3
Views: 699
Reputation: 19680
you need to pass a callback down from HomeScreen
to ProfileScreens
this callback would be called within ProfileScreens
and trigger HomeScreen
state change:
in HomeScreen
:
...
<ProfileScreens changeHomeScreen={() => this.setState({...})}/>
...
then in ProfileScreens
:
...
<Button title="decrementss" onPress={()=>{ this.props.changeHomeScreen() }}/>
...
Upvotes: 1