I have a GlobalContext.js file. I want to reach this part by having a variable named "global" in my MainScreen. But it doesn't see it. Where could be my mistake?
I thought what I did was correct, but it doesnt work
Here is GlobalContext.js
import React, { createContext, useContext, useState } from 'react';
import HorizontalCircles from "../components/HorizontalDiscussion";
import HorizontalDiscussion from "../components/HorizontalDiscussion";
export const GlobalContext = createContext();
function GlobalContextManager(props) {
const GetUsers = () => {
const returnFromService = {
"errorCode": -1,
"data": {
"colors": [
{
colorFirst:"red",
colorSecond:"black",
},
{
colorFirst:"pink",
colorSecond:"gray",
}
]
}
};
if (returnFromService.errorCode === -1) {
const returnFromGlobal = returnFromService.data.colors;
return returnFromGlobal;
} else {
return returnFromService.errorCode;
}
}
return (
<GlobalContext.Provider value={{ GetUsers }}>
{props.children}
</GlobalContext.Provider>
);
}
export default GlobalContextManager;
and here is the related part of MainScreen.js
import { GlobalContext } from '../../context/GlobalContext';
const MainScreen = ({ navigation }) => {
const global = useContext(GlobalContext);
// here is skeleton
const [users, setUsers] = useState([
<HorizontalCircles
skeleton={true}
key={0}
colorFirst={'rgb(' + 100 + ',' + 100 + ',' + 100 + ')'}
colorSecond={'rgb(' + 100 + ',' + 100 + ',' + 100 + ')'}
/>,
<HorizontalCircles
skeleton={true}
key={1}
colorFirst={'rgb(' + 100 + ',' + 100 + ',' + 100 + ')'}
colorSecond={'rgb(' + 100 + ',' + 100 + ',' + 100 + ')'}
/>,
]);
const getUsers = () => {
console.log("users from global:",global.GetUsers());
const g_users = global.GetUsers(); // when i ctrl click on GetUsers() it says any...
const tmpUsers = g_users.map((a,index) => <HorizontalCircles key={index} colorFirst={a.colorFirst} colorSecond={a.colorSecond} />)
setTimeout(() => {
setUsers(tmpUsers);
}, 5000);
}
useEffect(() => {
getUsers();
}, [])
and i wrote {users}
somewhere in return in MainScreen.js
here is HorizontalCircles.js
import React from "react";
import { View, Text, TouchableOpacity, TouchableHighlight } from "react-native";
const HorizontalCircles = (props) => {
return (
// added TouchableHighlight to have more clickable area around circles
<TouchableHighlight onPress={() => console.log("Circle is clicked")}>
<View style={{ position: 'relative', height: 50, width: 50, borderColor: "white", borderWidth: 1, backgroundColor: props.colorFirst, elevation: 3, borderRadius: 25, marginHorizontal: 10, }} >
<View style={{ position: 'absolute', right: 0, height: 15, width: 15, backgroundColor: props.colorSecond, borderRadius: 25, marginTop: 32 }} />
</View>
</TouchableHighlight>
/* when i give elevation for the first View, the small circles lose a bit of their position */
)
};
export default HorizontalCircles;
See Question&Answers more detail:
os