Hi I have a useEffect question/bug in my code. I would like to have a custom input field to upload an image. So I use useRef and pass it to the ProfileImageOption component. After the upload component the image's get url (avatarUrlPut) is updated and useEffect should call the getPhoto() function and re-render the component. But it is not happenning.
I have found this blogpost related to my issue. But blogpost is not providing a solution idea around the bug. https://coder.earth/post/react-hooks-oops-part-3-an-effect-does-not-run-again-when-its-dependencies-change
I have read from the official documentation that when useRef is used, useEffect will not be able to re-render the component because useRef doesn't notify React when it's current property changes. I suspect a similar issue here but I didn't understand it completely. Would someone help? Thank you.
function EmployeeHeader(props) {
const {avatarUrlPut, avatarUrlPost} = props
const dispatch = useDispatch()
const userID = useSelector((state) => state.auth.fetchUserSuccess.id)
useEffect(() => {
// After uploading the image avatarUrlPut is changed and it is on the dependency array of useEffect
dispatch(getPhoto(avatarUrlPut))
console.log("Am I called after an upload?") // No!
}, [dispatch, avatarUrlPut])
const [uploadedImage, setUploadedImage] = useState({})
const uploadImage = useRef()
const openCameraModal = useRef()
return (
<div>
<ColorizedRect width={'100%'} height={'175px'}>
<Image
source={avatarUrlPut}
className={'profile_image'}
spinnerwidth={'140px'}
spinnerheight={'175px'}
/>
<ProfileImageOption
onClick={() => uploadImage.current.click()}
icon={'upload'}
top={'80px'}
></ProfileImageOption>
<input
id="uploadAvatar"
ref={uploadImage}
type="file"
accept=".jpg,.jpeg,.png,"
style={{display: 'none'}}
onChange={(e) =>
dispatch(uploadPhoto(e.target, avatarUrlPost, setUploadedImage, handleShow))
}
/>
<a href={avatarUrlPut} download="Avatar.jpg">
<ProfileImageOption icon={'download'} top={'125px'}></ProfileImageOption>
</a>
</ColorizedRect>
</div>
)
}
export default EmployeeHeader