0

i saw several topics talking about this common mistake, but i didn't find nothing related to the use of recompose.

Context

I've this withStateHandler

withStateHandlers(
    {
      bookingValidation: false,
    },
    {
      setBookingValidation: ({ bookingValidation }) => () => ({
        bookingValidation: !bookingValidation,
      }),
    },
  ),

and i've this lifeCycle

lifecycle({
    componentDidMount() {
      const { getFamily } = this.props;
      getFamily();
    },
    componentWillReceiveProps(prevProps) {
      const { formValues } = prevProps;
      const { setBookingValidation } = this.props;
      const {
        locationId,
        specialityId,
        serviceId,
        cancellationDetails,
        personId,
        date,
      } = formValues;

      const allFormValuesSelected = !!(
        locationId &&
        specialityId &&
        serviceId &&
        cancellationDetails &&
        personId &&
        date
      );

      if (allFormValuesSelected) setBookingValidation();
    },
  }),

it's a simple validation, when i've all the selectedValues, the state of bookingValidation will change on true and you will be able to click on a button.

Problem

When you enter in this if if (allFormValuesSelected) setBookingValidation(); the maximum update depth exceeded because of the function setBookingValidation()

Question How can i avoid this behavior ? There is a way to maintain this function ?

Legeo
  • 784
  • 4
  • 20
  • 44
  • Your code is fine, just make sure `setBookingValidation()` is not called in an infinite loop. The simplest solution is to have another state flag and update that after the first call for `setBookingValidation()` and before you call it again in `componentWillReceiveProps()` you can verify if the execution is for the first time. – Amin Paks Nov 04 '19 at 11:54

1 Answers1

1

It happens because setBookingValidation() changes property value and calls componentWillReceiveProps. And you got an infinite loop of calls.

If you want to perform form validation, you should move that functionality into a separate withHandlers() method and call onChange event.

Andriy Budzinskyy
  • 1,971
  • 22
  • 28
  • could you give me an example ? i tried to follow your advices and write some code, but I received the same error. If you want i can update the question – Legeo Nov 04 '19 at 11:41