How to update initialParams in React Navigation?

Viewed 662

I have an app with array getting from storage and passing it to screen

Here is a bare version. Here if getItem is late, after rendering the screen array updates automaticly

import React from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage'

import Vocabulary from "./Screens/Vocabulary";

export default function App() {
  const [ vocabulary, setVocabulary] = React.useState([]);

  React.useEffect(() => {
    AsyncStorage.getItem('@vocabulary').then(value => setVocabulary(value !=null ? JSON.parse(value) : []) )
  }, []);
    
  return (
    <VocabularyWithEdit vocabulary={vocabulary} />
  );
}

Then I tried to use React Navigation and set array in initialParams

import React from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage'
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'

import Vocabulary from "./Screens/Vocabulary"

export default function App() {
  const [ vocabulary, setVocabulary] = React.useState([]);

  React.useEffect(() => {
    AsyncStorage.getItem('@vocabulary').then(value => setVocabulary(value !=null ? JSON.parse(value) : []) )
  }, []);
  const Stack = createStackNavigator()
    
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Vocabulary" component={Vocabulary} initialParams={{ vocabulary: vocabulary, str: "hey" }}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
}

But there array wasn't updated after rendering and set as [] or sometime i got undefinded

Please let me know how to fix it and make params update

2 Answers

I suggest passing the vocabulary data as props to the Vocabulary component. If you prefer using the initial params, you could use setParams to update them later.

For anyone facing this issue, you can use children instead of component to pass props to Screen. This way, when the state gets updated in the App, the updated values will be passed to the Screen.

For example, instead of:

<Stack.Screen name="Vocabulary" component={Vocabulary} initialParams={{ vocabulary: vocabulary, str: "hey" }}/>

use this:

<Stack.Screen name="Vocabulary" children={() => <Vocabulary vocabulary={vocabulary} str="hey" />} />

Docs here.

Related