I'm fairly new to React Native and I have created a Drawer Navigator in my App.js file.
One of my navigation components is named LifeScreen.
I am trying to pass a function to update a state (setSavedQuotes) to LifeScreen so that in LifeScreen I can update the value of the state (savedQuotes). This is straightforward in React but I can't seem to be able to do the same in React Native.
App.js (Navigator)
const App = () => {
const [savedQuotes, setSavedQuotes] = useState([])
return (
<NavigationContainer>
<Drawer.Navigator>
<Drawer.Screen
name="Home"
component={HomeScreen}
initialParams={{ sam: savedQuotes }}
/>
<Drawer.Screen
name="Life"
component={props => {
return <LifeScreen props={props} setSavedQuotes={setSavedQuotes} />
}}
/>
<Drawer.Screen name="Work" component={WorkScreen} />
<Drawer.Screen name="Saved" component={SavedScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}
LifeScreen.js
const LifeScreen = ({ route, setSavedQuotes }) => {
const [quote, setQuote] = useState('')
const lifeWisdom = [...] // array of quotes
const getQuote = () => {... } // get Random Quote
const saveQuote = () => {
// console.log('life:', route.params)
console.log("function: ", setSavedQuotes); // returns undefined
}
return (
<View style={styles.mainContainer}>
<TouchableOpacity onPress={getQuote} style={styles.quoteContainer}>
<Text style={styles.quote}>{quote}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={saveQuote} style={styles.imgContainer}>
<AntDesign name="hearto" size={40} color="black" />
</TouchableOpacity>
</View>
);
};
Whenever I console.log(setSavedQuotes), I get undefined.
I can pass props and the state value without any problem, as I did with HomeSCreen in App.js. I tried the following: regarding props, initialParams, react-navigation and route. I can manage to pass the state with all of them, but not the function to update the state.