0

How to rewrite the function so that it is updated and loaded every time you change pages. The fact is that the loading function works only on one page, but it does not pass to others, how to change it?

function loadModel(model) {
  return function(dispatch) {
    dispatch(moveToPending(model))

    const resource = require(`../resources/${model}`)
    const resourceActions = bindActionCreators(resource.actions, dispatch)
    const toaster = new Toaster(dispatch)

    return new Promise((resolve, reject) => {
      resourceActions[getFunctionName(model)]()
        .then(res => {
          resolve(model)
          dispatch(resolveSubscriptions(model))
        })
        .catch(err => {
          if (debug) console.error(err)
          reject({ ...err, model })
          dispatch(resolveSubscriptions(model))
          toaster.error(`Could not load ${model}!`)
        })
      })
  }
}

Update. Here's the componentWillMount(), I already have it, what do I need to add to it?

  componentWillMount() {
    this.props.actions.subscribe(this.subscriptions)
      .then(() => {
        this.props.actions.fetchRegisters({year: this.state.currentYear, month: defaultMonths()})
          .then(() => {
            if (!this.props.registers.length) {
              this.toaster.warning('There is no data for charts')
            }
            this.createReportState()
          })
      })
  }
andrea2010
  • 338
  • 2
  • 15

1 Answers1

0

React has some lifecycle methods. You can use componentWillMount or componentDidMount for this purpose. You can pass this function as a prop to other pages and there you can call it in componentWillMount, something like:

componentWillMount() {
  this.props.loadModel(//arg);
}

For reference: Component life-cycle methods

Arslan Tariq
  • 2,478
  • 2
  • 22
  • 45
  • 1
    you should refrain from using componentWillMount to load data -> see https://stackoverflow.com/questions/49206280/componentwillmount-is-deprecated-and-will-be-removed-in-the-next-major-version-0 for reference – deowk Aug 08 '18 at 08:07
  • This did not help me get the data on the page. – andrea2010 Aug 08 '18 at 08:17