Search code examples
react-nativereact-navigationreact-native-iosasyncstoragestack-navigator

How to fetch data in a component which is using StackNavigator in react-native?


Here is what I am trying to do for an iOS app using react-native -

  1. I am using StackNavigator
  2. In the home screen, I show all the items in a list which is get/fetch from AysncStorage. This is done in the componentDidMount(). This works fine.
  3. I go to a next screen (using StackNavigator) to add a new item to the list in the AsyncStorage. Item is added.
  4. When I come back to the home screen using the back button, the updated list is not shown. Also, the componentDidMount() is not called.

How can this issue be solved?


Solution

  • Redux is the best option but a dirty workaround is the following:

    Home screen

    state = { items: [] }
    
    addItemFromChild = (item) => {
       this.setState((prevState) => ({ items: [...prevState.items, item] }))
    }
    
    goToAddItemScreen = () => {
       this.props.navigation.dispatch(NavigationActions.navigate({ routeName: "AddItemScreen", params: { addItemFromChild: this.addItemFromChild } }))
    }
    

    AddItemScreen

    addItem = (item) => {
       this.props.navigation.state.params.addItemFromChild(item)
    }