0

I have simple click handler and it works in this case:

        handleClick = () => {
            const { isCalendarOpen } = this.state;

            this.setState ({ isCalendarOpen: !isCalendarOpen });
        };

But I must use callback function in setState, so I try this way:

       this.setState(state => ({
           isCalenderOpen: !state.isCalenderOpen
       }));

It's not wirking :( can someone suggest how to solve the problem?

2
  • "t's not wirking :(" not working how? How do you check it is working? Remember setState is async. Commented Dec 10, 2018 at 8:13
  • 1
    Also you have a typo isCalend**e**rOpen vs isCalend**a**rOpen Commented Dec 10, 2018 at 8:13

1 Answer 1

2

In setState, second argument is the callback function which will be called after state has been set. The first argument is either the object to which state would be updated or a function which will return the updated state. In both of your cases you are updating the state. It should be

this.setState ({ isCalendarOpen: !isCalendarOpen }, () => {
  // callback function
});

or

this.setState(state => ({
       isCalenderOpen: !state.isCalenderOpen
   }), () => {
  // callback function
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.