0

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.

Lorenzo
  • 64
  • 8
  • try this one, https://stackoverflow.com/questions/60114496/passing-function-as-a-param-in-react-navigation-5 – Wen W Nov 24 '20 at 23:34
  • @WenW Using that answer and the documentation [here](https://reactnavigation.org/docs/navigation-prop/) I can pass values back to another Screen and update the value of my hook there. It can be a solution. As a side effect, it brings me to that Screen. – Lorenzo Nov 25 '20 at 12:54
  • awesome, i'm glad you found a solution. :) – Wen W Nov 25 '20 at 13:42

0 Answers0