Using Async Storage with React Navigation (React Native)

Viewed 106

Looking to utilize Async Storage in a Mobile Application, but having a hard time figuring out how to pass state as props through Navigation after lifting it up to the "root" file.

Here is an example I found that would work independent of Navigation:

const [ "state", "setState" ] = useState(state);

... 

return (

   <Container>
     <Home state={state} setState={setState}/>
   </Container>

)

Here is what i've tried with Navigation:

 const [ "state", "setState" ] = useState(state);


  <NavigationContainer>
    <Stack.Navigator>
       <Stack.Screen name ='Home' >
         {props => <Home state={state} setState={setState}/>}
       </Stack.Screen>
    </Stack.Navigator>
  </NavigationContainer>

If needed to provide more for context, will do - just let me know. thanks in advance

1 Answers

Work examples you can try in here https://snack.expo.io/@vasylnahuliak/great-bubblegum

import 'react-native-gesture-handler';
import React, { useState } from 'react';
import { Text, View, StyleSheet, Button, FlatList } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const HomeSceen = ({ route, navigation, counter, setCounter }) => {
  return (
    <View>
      <Text>Counter: {counter}</Text>
      <Button title="Increase" onPress={() => setCounter(prevCounter => prevCounter + 1)} color="green" />
      <Button title="Decrease" onPress={() => setCounter(prevCounter => prevCounter - 1)} color="tomato" />
    </View>
  );
};

const Stack = createStackNavigator();

const App = () => {
  const [counter, setCounter] = useState(0);

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="HomeSceen"
          component={(props) => (
            <HomeSceen counter={counter} setCounter={setCounter} {...props} />
          )}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;
Related