React useState value in combination with useEffect

I am working on a little project on React. Basically, you enter any string and a QR code gets generated for you. The issue that I have is that my Form input that uses useState does not trigger the useEffect on change. Thank you in advance, Below is the code:

const Addtoform= () => {
  
  
    const [text, setText] = useState('');
    const handleSubmit = (e) => {
     e.preventDefault();
     console.log(text);
     
    }

    

    

    const [src, setSrc] = useState('');
   
    useEffect(() => {
     QRCode.toDataURL(text).then((data) => {
         setSrc(data);
     });
  
    }, []);

return (
    <>
      <img src={src} />
    <p> Text: {text}</p>
    <form onSubmit={handleSubmit}>
    <input type="text" value={text} required onChange={(e) => setText(e.target.value)}/>
    <input type="submit" />
    </form>
    </>
   );
 };

export default Addtoform ;

>Solution :

You need to put ‘text’ in the [] as a parameter, in order to trigger the side effect every time the text changes

Leave a Reply