Wait for the promise from the father component from the kids in the reactor

I'm trying to implement a React app using a Container / Presentation Template (aka Smart / Dumb components).

To put it simply, I have a presentation component that shows and hides a modal. There is a form in the modal form, after the user submits the form from the Presentation Component, I call the Container (via the prop). At this point, the container makes an AJAX request.

To do this in a more visual way, this happens:

modal submit -> Presentational calls Container -> Container makes AJAX call

      

After the AJAX call completes, I need to notify the presentation component so that it can hide the modal.

The way I have implemented it is as follows:

// In Presentational.jsx
handleModalSubmit() {
  this.props
  .onSubmit()
  .then(() => this.setState({ isModalOpen: false }))
}

// In Container.jsx
handleSubmit () {
  return fetch(/*...*/).then(/* handle the data */)
}

      

You can see it in action here https://www.webpackbin.com/bins/-Kl3oN5Hua4cxwmZx4Qo

My question is, is it okay for a parent to return a promise to a child, or is there a more reactive way to do this?

+3


source to share


1 answer


There is nothing wrong with what you do.

Another option is to move the isModalOpen state to the parent component and then just pass it to the child through the prop. At this point, Presentational.jsx is truly a presentation component. Generally, when it comes to smart / dumb or containers / presentation components, all state lives in the parent and dumb components, which are simply rendered based on the props they receive.



The advantage here is that your Presentational.jsx can now be used in situations where you don't want to use a promise when submitting a modal. Moreover, you may have other logic that can also close a modality other than dispatch. This way you end up with a component with a lot of reusability potential because it takes less.

The trade-off, however, is that since you accept less, your component no longer contains logic for what is likely a common model in your application (feed returns a promise and closes the modal when the solution promises). To get the best of both worlds, you can have your stateless component and then create a simple wrapper around it that currently contains the isModal state management. With stateless and stateless components, you can handle both the general case when you just want the modal to be closed and decide to send a promise, and the case when you need something a little different but look the same.

+2


source







All Articles