Darren Cooney
Darren Cooney

Reputation: 1060

React state not correct when function called via addEventListener

I have a React component that uses state to manage a changed variable if a form input is updated.

Assuming I've made some updates to the form, the issue I'm having is if I dispatch a click event to the onCancel function using addEventListener the value of changed is not correct but if I call onCancel from the JSX the value is correct.

Any ideas?

const Edit = (props) => {
  let [changed, setChanged] = useState(false);

  // Fired when a form value is updated
  const onChange = (e) => {
    setChanged("true");
  };

  // Close modal
  const onCancel = () => {
    console.log(changed); // This will be false when triggered from addEventListener
  };

  useEffect(() => {
    let form = document.querySelector(".oda-edit-form");
    // Close Window on click outside
    form.addEventListener("click", function () {
      onCancel();
    });
  }, []);

  return (
    <div>
      <input type="text" onChange={(e) => onChange(e)} />
      <button onClick={onCancel}>Close</button>
    </div>
  );
};

Upvotes: 0

Views: 33

Answers (2)

Darren Cooney
Darren Cooney

Reputation: 1060

Removed the addEventListener and added an onClick directly to the JSX with a custom method.

const Edit = (props) => {
  let [changed, setChanged] = useState(false);

  // Fired when a form value is updated
  const onChange = (e) => {
    setChanged("true");
  };

  // Close modal
  const onCancel = () => {
    console.log(changed); // This will be false when triggered from addEventListener
  };

  const onClickOutside = (e) => {
    let element = e.target.querySelector('.wide-card');
    let isClickInside = element.contains(event.target);
    // // Close Modal
    if (!isClickInside) {
        onCancel();
    }
   };

  return (
    <div onClick-{(e)=>onClickOutside(e)}>
      <input type="text" onChange={(e) => onChange(e)} />
      <button onClick={onCancel}>Close</button>
    </div>
  );
};

Upvotes: 0

Karan Kumar
Karan Kumar

Reputation: 3176

You need to re render your component as soon your state changes to run the onCancel() funtion.

    let form = document.querySelector(".oda-edit-form");
    // Close Window on click outside
    form.addEventListener("click", function () {
      onCancel();
    });
  }, [changed]);  // < ----- add dependancy

Upvotes: 1

Related Questions