Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update initialParams in React Navigation?

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

like image 230
Dan Avatar asked Aug 04 '26 12:08

Dan


2 Answers

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.

like image 185
Placid Avatar answered Aug 07 '26 00:08

Placid


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.

like image 31
Mehrad Avatar answered Aug 07 '26 02:08

Mehrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!