Mark Shust at M.academy
Mark Shust at M.academy

Reputation: 6429

How do I setState within React's recompose's lifecycle method?

I am using recompose in my React project https://github.com/acdlite/recompose/

It's a great library. I'm using the compose utility as a container component that passes state down as props to the presentational component like so:

const enhance = compose(
  lifecycle({
    componentDidMount() {
      myCall
        .getResponse([productId])
        .then(products => {
          setIsReady(true);
        });
    },
  }),
  withState('isAvailable', 'setIsAvailable', false),
  withState('isReady', 'setIsReady', false),
  mapProps(({
    setIsAvailable,
    setIsReady,
    ...state,
  }) => ({
    onLogoutTouchTap: () => {
      ...

Note the setIsReady(true) call within componentDidMount. This is what I want to do, however lifecycle/componentDidMount doesn't have access to setIsReady. How can I accomplish my intended result of updating state from componentDidMount with recompose?

Upvotes: 15

Views: 4898

Answers (1)

Mark Shust at M.academy
Mark Shust at M.academy

Reputation: 6429

Well I found out if you move the lifecycle method after the withState methods, you have access to the setters by accessing this.props.setterFunction. In my case, here is the solution I was looking for:

const enhance = compose(
  withState('isAvailable', 'setIsAvailable', false),
  withState('isReady', 'setIsReady', false),
  lifecycle({
    componentDidMount() {
      myCall
        .getResponse([productId])
        .then(products => {
          this.props.setIsReady(true);
        });
    },
  }),
  mapProps(({
    setIsAvailable,
    setIsReady,
    ...state,
  }) => ({
    onLogoutTouchTap: () => {
      ...

Upvotes: 18

Related Questions