I want to call below mentioned function onSaveInputValue into the useEffect so that, my component can have passed value in childInputValue hook whenever the page gets loaded.
const onSaveInputValue = (value) => {
setChildInputValue(value);
console.log(childInputValue);
};
I have tried to do so but couldn't do it. Please guide me.
In case if you like to see the full code of components then it is mentioned as below.
Parent Component:-
import { useEffect, useState } from "react";
import Child from "./Child";
const Parent = () => {
const [childInputValue, setChildInputValue] = useState();
// useEffect(() => {});
const onSaveInputValue = (value) => {
setChildInputValue(value);
console.log("childVInputValue",value)
};
return (
<div>
<h1>Parent Component</h1>
<p>{childInputValue}</p>
{/* We pass function to the child component. */}
<Child onSaveInputValue={onSaveInputValue} />
</div>
);
};
export default Parent;
Child Component:-
import React, { useEffect, useState } from "react";
import "./App.css";
function Child(props) {
const [baseImage, setBaseImage] = useState("");
const uploadImage = async (e) => {
const file = e.target.files[0];
const base64 = await convertBase64(file);
setBaseImage(base64);
props.onSaveInputValue(baseImage);
};
const convertBase64 = (file) => {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = () => {
resolve(fileReader.result);
};
fileReader.onerror = (error) => {
reject(error);
};
});
};
useEffect(()=>{
console.log("useeeffect",baseImage)
})
return (
<div >
<input
type="file"
onChange={(e) => {
uploadImage(e);
}}
/>
<br></br>
<img src={baseImage} height="200px" />
<hr/>
</div>
);
}
export default Child;