Update component on navigator.pop ()

I am using React Native Navigator. Is there a need to update the component at all, so when I get back to it, it will make a new API call and take the updated data to display in the component. I found several similar questions, but did not find a good answer ...

+4
source share
4 answers

When pop () refreshes before the page is a good idea

You can try DeviceEventEmitterobject

  • previous page DeviceEventEmitter.addListener('xxx', callback)incomponentDidMount
  • current page DeviceEventEmitter.emit('xxx', anythingInCallback...)topop()

ps: previous page DeviceEventEmitter.removeAllListeners('xxx')incomponentWillUnmount

+2
source

.

this.props.navigator.push({
          name: *nextscene*,
          passProps: {
            text: response,
            callBack: this.callback
        });

async callback(){
   await ....//make new api request grab the udpated data
}

, .

 this.props.callBack()
 this.props.navigator.pop()
+1

, , . React Native, - .

React Navigation API docs ! ! .

, StackNavigator. API. StackNavigator pop.

handleSubmit = () => {
  const { value, otherValue } = this.state
  addThingToDatabase({ value, otherValue })
    .then(() => this.props.navigation.pop())
}

, "" StackNavigator. "pop". ComponentDidMount.

componentDidMount() {
  const { index } = this.props.navigation.state.params

  getAllThingsFromDatabase({ index })
    .then(({ arrayOfThings }) => this.setState({
      index,
      arrayOfThings
  }))
}

But the Component was not updated with the new thing until addListener! Now I have almost the same code, except for it in the constructor. I decided that I only need to run it once, and I also need to store it.

constructor(props, context) {
  super(props, context)

  this.state = {
    index: null,
    arrayOfThings: []
  }

  this.willFocusSubscription = this.props.navigation.addListener(
    'willFocus',
    (payload) => {
      const { index } = payload.state.params
      getAllThingsFromDatabase({ index })
        .then(({ arrayOfThings }) => this.setState({
          index,
          arrayOfThings
        }))
    }
  )
}

Please note that the docs also mention unsubscribing from the event listener using the function .remove(). I put it in ComponentWillUnmount().

componentWillUnmount() {
  this.willFocusSubscription.remove()
}

There are four different events for a subscription. I went with willFocus, thinking that it will be updated before the screen appears.

0
source

Source: https://habr.com/ru/post/1662672/


All Articles