Hi - I submitted this same question in Stack Overflow so apologies to those that are seeing this twice. But the post did not get any traction there and I am just as stuck with the problem now as I was then.
This is the post copied/pasted here:
I have a React Native app which has 3 screens: parent
, child-1
, child-2
. The parent
screen has direct links to 2 screens: child-1
, child-2
. Child-1
screen has the code that fills in the state for a Variable X
. Then Child-2
screen displays the values from Variable X
.
So obviously I am running into a problem where if the user loads the app and goes straight from Parent
to Child-2
, the app crashes because Variable X
is empty (and actually does not even exist). I have tried two ways to fix this:
- React Context API; but this results in undefined
Variable X
no matter what route the user takes. Github code. (Parent
screen =WelcomeScreen.js
,Child-1
=BuildPantry.js
,Child-2
=ResultingRecipes.js
)
This is the important code:
From WelcomeScreen.js
:
function WelcomeScreen(props) {
const data = useContext(WinRecipeContext);
console.log(data); //This returns undefined
//more stuff
}
From BuildPantry.js
:
import WinRecipeContext from "./../context/winRecipeContext";
function BuildPantry(props) {
//a bunch of code that build the variables I need based on user choice
return (
<WinRecipeContext.Provider value={"Placeholder: replace with actual data"}>
<View>
//more React components to display
);
}
From winRecipeContext.js
:
import React from "react";
const WinRecipeContext = React.createContext();
WinRecipeContext.displayName = "WinRecipeContext";
export default WinRecipeContext;
- I also tried to initialize a separate variable set in
Parent
that is fed by a callback function fromChild-1
. But can I even do that?? I.e. load data inParent
fromChild-1
component. Would I use a hook (useEffect
) to load the data in as soon asParent
loads into view…?? Code for this is only on local drive but happy to upload if this is more promising…??
Help!