Why datas not update after navigate on react native?

2.1k Views Asked by At

I have a basic tab navigation HOME-UPLOAD-PROFILE. 'HOME' screen has values which fetch with an api from a different web site. After user log in navigation system direct user to this home page and "fetch" working well. But when i upload something using 'UPLOAD' screen and then return 'HOME' screen datas not updating. Whereas 'componentDidMount' should works everytime and bring datas every clicking 'HOME' screen I could not find any solution or answere

export default class Home extends Component {
  state = {
    data: []
  };
  async componentDidMount() {
    //Burada kullanıcı yoksa ülkeleri getireceğiz
    const rest = await fetch(
      'https://www.birdpx.com/mobile/fotografgetir/' + this.state.page,
      {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-type': 'application/json'
        },
        body: JSON.stringify(datam)
      }
    );

    const gelenVeri = await rest.text();
    let convertedVeri = JSON.parse(gelenVeri);

    this.setState({
      data: convertedVeri
    });
  }
}
2

There are 2 best solutions below

0
On

If you are using react-navigation, components do not unmount when you navigate from one screen to the next on a stack navigator. You can listen to navigation lifecycle events in a component (https://reactnavigation.org/docs/4.x/navigation-prop/#addlistener---subscribe-to-updates-to-navigation-lifecycle)

or if you are using withNavigationFocus HOC for passing navigation prop to a component you can use the isFocused prop to know about the recent focus on you component.

0
On

You can check by logging if componentDidMount is triggered.

componentDidMount won't be triggered when you navigate between tabs in tabNavigator, except for the first time when tabNavigator is mounted.

You can choose one of the following 2 ways to implement what you need.

1. Use global redux state instead of component state. (Recommended)

You can implement redux to your project (if you aren't using). Use redux state in Home component instead of current component state.

On Upload screen, once uploading is done you can change the redux store by dispatching an action. This will instantly reflect on your Home component.

2. Fetch data on component focus event

If you want to catch the focus event for a specific tab component, you can use didFocus event listener of navigation lifecycle.

const didFocusSubscription = this.props.navigation.addListener(
  'didFocus',
  payload => {
    console.debug('didFocus', payload);
  }
);

// Remove the listener when you are done
didFocusSubscription.remove();