I have created useContext and want to update it in one tab screen and recieve it in others tab screens.
I created Context file
import React, { createContext } from "react";
export const ChampContext = React.createContext('test');
In Home screen Im recieving useContext and updating it on select. After updating it successfully displays updated context value. Here is code from Home.js
import React, { useEffect, useState, useContext } from "react";
import { View, Text, StyleSheet, TouchableOpacity, Picker } from 'react-native';
import SelectDropdown from 'react-native-select-dropdown'
import { ChampContext } from '../../../ChampContext'
const countries = ["third", "second", "first"]
const Home = ({ navigation }) => {
const [championship, setChampionship] = useState(useContext(ChampContext))
return (
<View style={styles.container} >
<View style={styles.header}>
<View style={{ height: '100%', width: '50%', justifyContent: 'center', }}>
<Text style={{ fontWeight: 'bold', fontSize: 15, }}>Select Championship</Text>
</View>
<SelectDropdown
data={countries}
onSelect={(selectedItem, index) => {
setChampionship(selectedItem)
}}
buttonTextAfterSelection={(selectedItem, index) => {
// text represented after item is selected
// if data array is an array of objects then return selectedItem.property to render after item is selected
return selectedItem
}}
rowTextForSelection={(item, index) => {
// text represented for each item in dropdown
// if data array is an array of objects then return item.property to represent item in dropdown
return item
}}
/>
</View>
<Text>Context value: {championship}</Text>
</View >
)
}
export default Home
But when recieving the same context in game screen it is still default value which is 'test'. What am I doing wrong?
Here is code from Game.js screen:
import React, { useEffect, useState, useContext } from "react";
import { View, Text, StyleSheet, TouchableOpacity, Button } from 'react-native';
import { ChampContext } from '../../../ChampContext'
const Game = ({ navigation, route }) => {
const championship = useContext(ChampContext)
// const [championship, setChampionship] = useContext(ChampContext);
return (
<View style={styles.container} >
<Text>Game Screen</Text>
<Text>context: {championship}</Text>
<Button onPress={() => navigation.navigate('SelectRiders', { champ: championship })} title="open" />
</View >
)
}
export default Game
CodePudding user response:
Did you wrap your components into context provider? You did not show your root comonent.
Like in documentation, you must wrap your components into context provider.
If you have Navigation, you can wrap it into provider.