fahad19 / proppy

Functional props composition for UI components (React.js & Vue.js)
https://proppyjs.com
MIT License
939 stars 27 forks source link

Feature: lifecycle hoc #19

Closed armand1m closed 6 years ago

armand1m commented 6 years ago

Currently, recompose offers us the lifecycle hoc where we can do stuff such as

import React from 'react'
import PropTypes from 'prop-types'
import { lifecycle } from 'recompose'

import Contact from '../Contact'
import ContactPropType from '../PropTypes/Contact'

const withContacts = lifecycle({
  componentDidMount() {
    fetch('https://randomuser.me/api/?results=20')
      .then(response => response.json())
      .then(data => data.results)
      .then(contacts => this.setState({ contacts }))
  }
})

const Contacts = ({
  contacts
}) => (
  <div className="contacts">
    {contacts.map(contact => (
      <Contact
        key={contact.id.value}
        contact={contact}
      />
    ))}
  </div>
)

Contacts.propTypes = {
  contacts: PropTypes.arrayOf(ContactPropType)
}

Contacts.defaultProps = {
  contacts: []
}

export default withContacts(Contacts)

And I just realized that proppy nor proppy-react have an option for this. Is this part of the roadmap? Any opinions are welcome :smile:

armand1m commented 6 years ago

Just saw the https://proppyjs.com/docs/lifecycle/ page, will try using the didSubscribe =)

armand1m commented 6 years ago
import React from 'react'
import PropTypes from 'prop-types'
import { compose, withState, didSubscribe } from 'proppy'
import { attach } from 'proppy-react'

import Contact from '../Contact'
import ContactPropType from '../PropTypes/Contact'

const withContacts = compose(
  withState('contacts', 'setContacts', []),
  didSubscribe(props => {
    fetch('https://randomuser.me/api/?results=20')
      .then(response => response.json())
      .then(data => data.results)
      .then(props.setContacts)
  })
);

const Contacts = ({
  contacts
}) => (
  <div className="contacts">
    {contacts.map(contact => (
      <Contact
        key={contact.id.value}
        contact={contact}
      />
    ))}
  </div>
)

Contacts.propTypes = {
  contacts: PropTypes.arrayOf(ContactPropType)
}

Contacts.defaultProps = {
  contacts: []
}

export default attach(withContacts)(Contacts)

This made the work :slightly_smiling_face: