I wrote a crop editor image profile but I want to change a state variable if file is picked up.
<input
type="file"
name="profilePicBtn"
accept="image/png, image/jpeg"
onChange={profilePicChange}
id="upload"
style={{display:"none"}}
/>
this is my input element and in continue we have
let test = document.getElementById('upload')
and my props are
<CropImage
imageSrc={selectedImage}
setEditorRef={editor}
onCrop={onCrop}
scaleValue={scaleValue}
onScaleChange={onScaleChange}
onTest={test}
/>
and in other component we have
const [isModalOpen, setIsModalOpen] = React.useState(false);
if (onTest != null) {
console.log('done')
setIsModalOpen(true)
}
but I got trapped in a infinite loop and receive this error
react-dom.development.js:16317 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
CodePudding user response:
You have to use React useEffect
for this purpose. And by using onTest
inside the dependency array of the useEffect
it will ensure useEffect
will be triggered in each time onTest
value is being changed. Probably in your scenario it will be called twice (from null
to given value).
const [isModalOpen, setIsModalOpen] = React.useState(false);
React.useEffect(()=> {
if(onTest != null) {
console.log('done')
setIsModalOpen(true)
}
}, [onTest])
CodePudding user response:
Manipulating state in every render causes another render. This is what you do with setIsModalOpen(true)
, hence the infinite loop. The condition if(onTest != null)
is probably always true.