I have a parent component that should be updated when the form on the child component is submitted. When the form is submitted in the child component, the fetchData function is being called, however, the data is not updated in the parent component here, and requires a page refresh to update the data:
{JSON.stringify(data)}
I cannot add the data from the setState to useEffect because it would create an infinite loop.
How do I update the data on the parent component when submitting the form from the child component?
parent component
export function ParentComponent() {
const [data, setData] = useState(null);
const fetchData = async () => {
const result = await axios(
'/api/info/'
);
setData(result.data)
}
useEffect(() => {
fetchData();
},[]);
return (
<div>
<h1>
Parent Page
</h1>
{JSON.stringify(data)}
<ChildComponent dataUpdated={fetchData} />
</div>
)
}
child component
export function ChildComponent(props) {
const [formData, setFormData] = useState('');
const handleSubmit = evt => {
evt.preventDefault();
axios.post(`/api/info/create`,
{formData}
)
.then(response => { return response.data })
.then(props.dataUpdated()) // calling this function does not update the data on the parent component
}
return (
<div>
<h1>
Child Component
</h1>
<form className={classes.form} onSubmit={handleSubmit}>
<TextField value={formData.number}
id="filled-number"
label="number"
type="number"
onChange={evt => setFormData({...formData, number: evt.target.value})}
/>
<Button
type="submit"
>
Submit
</Button>
</form>
</div>
)
}