Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React code keeps rerendering after changing state

this code keeps rerendering the page on every state change and when I add an image it keeps
rerendering infinitely without errors

const [adData, setAdData] = useState({
    name: "",
    link: "",
    fromDate: {},
    toDate: {},
    fromTime: {},
    toTime: {},
    iconEn: null,
    allViews: 0,
    userViews: 0,
  });
  const [iconEN, setIconEN] = useState(null);
  const [currentEnImg, setCurrentEnImg] = useState(null);
  const handleOnChange = (e) => {
    setAdData({ ...adData, [e.target.name]: e.target.value });
  };
  const handleOnCheck = (e) => {
    setAdData({ ...adData, [e.target.name]: e.target.checked});
  };
  if (iconEN) {
    const reader = new FileReader();
    reader.onload = () => {
      setCurrentEnImg(reader.result);
      setAdData({ ...adData, iconEn: iconEN });
    };
    reader.readAsDataURL(iconEN);
  }

what am I doing wrong and how to fix it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Issue is here:

if (iconEN) {
    const reader = new FileReader();
    reader.onload = () => {
      setCurrentEnImg(reader.result);
      setAdData({ ...adData, iconEn: iconEN });
    };
    reader.readAsDataURL(iconEN);
  }

every state set function re-render the application and on every re-render the same state set function is called that makes this process as a never ending loop.

Solution: try useEffect hook with a proper dependency variable or [] and this problem will be solved.

In your case put your login inside useEffect like:

useEffect(() => {
     if (iconEN) {
        const reader = new FileReader();
        reader.onload = () => {
          setCurrentEnImg(reader.result);
          setAdData({ ...adData, iconEn: iconEN });
        };
        reader.readAsDataURL(iconEN);
      }
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading