0

Suppose I have two screens: HomeScreen & LocationScreen

Steps: Firstly I navigated from HomeScreen(state={location: 'A'}) to LocationScreen.

Changed location in LocationScreen(state={location: 'B'})

Pass it to HomeScreen and change location from A to B.

Now , HomeScreen has View dependent on location state.

So my question is , how can I update the view content of home screen as the content is coming from network response after the location been updated?

Subhajit
  • 876
  • 3
  • 17
  • 37

2 Answers2

1

What you are suffering from is a common problem of state management in React. For easing your trouble, there is another library called Redux. Give it a read.

To answer your question, Redux provides a connect function which has two arguments : 1) mapStateToProps & 2) mapDispatchToProps. You can easily solve your problem with these two functions and a lifecycle method called "componentWillReceiveProps(nextProps)".

Here is an example you can refer to : https://stackoverflow.com/a/38203735/2164029

Caleb Tolu
  • 463
  • 4
  • 10
atitpatel
  • 3,104
  • 1
  • 24
  • 34
  • Thanks for the reply, but how can it help me to update the view content of home screen as the content is coming from network response after the location been updated? – Subhajit Jul 22 '17 at 06:12
  • Then you probably should start an Activity Indicator while requesting a network response and stop it as soon as you receive the response. Then you can update the view using state variables. – atitpatel Jul 22 '17 at 06:23
  • Redux was a good read. Does react native automatically re update(update means reloads the full component ) the component when there is a change in its state? – Subhajit Jul 22 '17 at 08:24
  • Yes, it does. That is the beauty. Also it only changes the part of the component which is affected by that state variable. – atitpatel Jul 22 '17 at 09:52
0

Redux is a great tool for app state management, especially for the state that is shared in a few places in the app.

In your use case though, I think the regular React state should be sufficient.

After you pass the changed location from Location screen back to Home screen, Home screen can in term trigger the fetching for data. By storing the content on the component state, you can easily refer to them in render function. this.setState triggers re-render of the component, as any state change or prop change will cause a re-render

e.g.

class HomeScreen extends Component {
  ...
  onLocationChange(newLocation) {
    this.setState({ loading: true, newLocation }); // Loading data, and storing new location
    fetchDataBasedOnLocation().then((data) => {
      this.setState({ content: data. loading: false });
    });
  }

  render() {
    return (
      ...
      {Your content in this.state.content}
      ...
    );
  }
}

Hope this is helpful!

hyb175
  • 1,291
  • 8
  • 13