The props to the child component is updating on handleOnChange
event. Below is sample code structure.
const { useCallback, useEffect, useState } = React;
//think this is coming from parent obj
const retrieveData = () =>
Promise.resolve({
English: { v1: "10", v2: "11", v3: "34" },
Hindi: { v1: "14", v2: "16", v3: "18" },
});
const createKey = (...values) => values.join("-");
const splitKey = (key) => key.split("-");
const App = ({ retrieveData }) => {
const [data, setData] = useState(retrieveData.English);
//this retrieveData.English always updating on handleChange
useEffect(() => {
retrieveData().then(setData);
}, []);
const handleChange = useCallback(({ target }) => {
const [lang, key] = splitKey(target.name);
setData((oldData) => {
const newData = { ...oldData };
newData[lang][key] = target.value;
return newData;
});
}, []);
return (
<form>
{Object.entries(data).map(([lang, item]) => (
<div key={lang} className="row">
<div className="head">{lang}</div>
<ul>
{Object.entries(item).map(([key, val]) => (
<li key={createKey(lang, key)}>
<label>{key}</label>
<input
name={createKey(lang, key)}
value={val}
onInput={handleChange}
/>
</li>
))}
</ul>
</div>
))}
</form>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
In the above case, the props obj value also updating on the handleChange
setData
. I am not sure what I am missing. I need to compare the initial obj values with handle change values. Any idea on this.
CodePudding user response:
in this way, the state will be updated with the data entered in the input.
const [initVal, setInitVal] = useState(obj.values)
const handleChange = (e) => {
setInitVal(e)
})
<input value={initVal} onChange={(e) => handleChange(e.target.value)} />
}
CodePudding user response:
Why used useEffect?
Try this.
const handleChange = (e) => {
setInitVal(e.target.value)
}