Hello StackOverflow Community
I am trying to update the state of a json object using setState in a child component but its not working. The data attribute is empty. What am I doing wrong?
App.JS
const [userData, setUserData] = useState({
firstName: "",
lastName:"",
email: "",
code:"",
})
return (
<div>
<Child parentInfo = {{userData, setUserData}} />
</div>
)
Child.js
function Child({parentInfo}) {
const client = axios.create({
baseURL: "http://localhost:7171/api/"
});
const handleSubmit = e => {
e.preventDefault();
client.post('public/someAPI',someData).then((response) => {
if(response.status === 200){
parentInfo.setUserData(prevData => ({...prevData,
code: response.data.code
}))
console.log(parentInfo) //NOT updated
//Store this data in localstorage but its not updatd??
//localstorage.setItem('key', parentInfo.userData);
});
}
return(
<header className="form-header">
<h2>{parentInfo.userData}</h2>
</header>
<form className="form flex-col" onSubmit={handleSubmit}>
<button type="submit" >Submit</button>
</form>
)
export default Child;
Where response is the same json but filled with some more data. But Code attribute is empty even after doing a setState though reponse.data contains a value for code. eg
response.data = {firstName: "test",
lastName:"test",
email: "test",
code:"123",
}