S
S
Shmebilock2019-08-13 14:11:11
React
Shmebilock, 2019-08-13 14:11:11

Can't update state in event callback?

the isActive state is not updated when handleClick is called.

const [isActive, setIsActive] = useState(false);
const [isDisabled, setIsDisabled] = useState(props.disabled);
const switchEl = useRef();

useEffect(() => {
  setIsDisabled(props.disabled);
  if (isDisabled) {
     switchEl.current.removeEventListener('click', handleClick);
  } else {
     switchEl.current.addEventListener('click', handleClick);
  }

  return () => switchEl.current.addEventListener('click', handleClick);
}, [props.disabled])

const handleClick = (event) => {
  event.stopPropagation();
  setIsActive(!isActive);
  props.onChange(!isActive);
  console.log('on click');
};

isActive is still unchanged after calling handleClick again. it is always false.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-08-13
@Shmebilock

Simplification example:

const Example = ({ disabled, onChange }) => {
  const [isActive, setIsActive] = useState(false);

  const handleClick = useCallback((e) => {
    e.stopPropagation();
    if (disabled) return;
    setIsActive(!isActive);
    onChange(!isActive);
  }, [isActive, disabled]);

  return <Switch onClick={handleClick} />;
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question