0

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;
  • 1
    Sorry, couldn't see any issue. Any error? – Bhojendra Rauniyar Jun 02 '21 at 15:01
  • thank you for replying. It says "undefined is not a object(evaluating global.GetUsers –  Jun 02 '21 at 15:22
  • 1
    Ah, where are you using `GlobalContextManager`? – Bhojendra Rauniyar Jun 02 '21 at 15:35
  • I just get GlobalContext from that page, as `const global = useContext(GlobalContext` and i have GetUsers function inside `GlobalContextManager` i thought i could be able to reach that function, but i couldnt as I see. How could I write then? i mean what should i write to do what i want? if i am clear. Thank you though, i guess you found it.. –  Jun 02 '21 at 16:21

2 Answers2

2

As per your comment,

GlobalContextManager must be used to or parent of MainScreen component. Since createContext has no default value when trying to access value with useContext, you will get undefined value.

Eg,

<GlobalContextManager>
   <MainScreen />
</GlobalContextManager>

Now, you can use the context in main screen component and you will get the value defined in the provider.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Thank you so much. Yeah I forgot to wrap my App.js around ` –  Jun 02 '21 at 19:53
  • I really appreciate it, thank you, it works now. Btw do you have any suggestion for me how i get better at react, react-native, and javascript? do u recommend any youtube or another online courses, or tutorials? –  Jun 02 '21 at 19:58
  • 1
    You'll experience as you go. – Bhojendra Rauniyar Jun 03 '21 at 03:29
  • Sir, Could u tell me what i am doing wrong? I try to add another function in my Context file, but when i add the other one, it doesnt see it? Is the problem in this Context.js page, or another? https://snack.expo.io/jBYMllWjg –  Jun 03 '21 at 05:10
  • 1
    Sorry, I was extremely busy today. Looking it now but page you linked is not loading. – Bhojendra Rauniyar Jun 03 '21 at 16:24
  • 1
    No problem Sir, i just found out my problem, thank you :) –  Jun 04 '21 at 06:49
  • Hello Mr, if my question is not answered when you have free time, could you look at it? its about java, and reaching postgres database https://stackoverflow.com/questions/68028527/how-can-i-reach-my-database-as-json-value-when-i-request-on-my-local –  Jun 18 '21 at 02:28
-1

In my project I started using react context and ended up getting rid of it as it seems not adding that much value and actually introducing unnecessary technical debt. I suggest just having a normal JavaScript context object that you import wherever you need. You can set the properties of this object to be instances of other classes or just simple values for whatever you need to use across your application. Those values can be set into that object from wherever in your application. Just my 2 cents.

andriusain
  • 1,211
  • 10
  • 18
  • Thanks for the answer. But i just try to learn react context. I mean i have to learn, but i couldnt do the basic thing i guess. –  Jun 02 '21 at 13:03
  • 1
    Fair enough, although there is a benefit of embedding React in your application's business logic rather than embedding your logic in React. If you do it the way I suggested you will not get unexpected re-renders when anything in the context changes, potentially making your app more optimised, although you will have to manually trigger those re-renders via subscription patterns. – andriusain Jun 03 '21 at 02:35
  • Thanks for the comment. Well I am intern at a company, i just try to learn things, and improve my knowledge.. Btw Id love if you could suggest any youtube or another online courses, or tutorials if there are ones u like. –  Jun 03 '21 at 04:50