I’m trying to pass data from a Parent component to a Child component that renders a table. Everything works fine the first time, but if I push refresh, the Child no longer sees the data. Any assistance with how to make the child see the data everytime is much appreciated. Below is my code. Thanks:
const Parent = () => {
const [data, setData] = useState([])
const getData = async(req, res)=>{
try{
const res = await axios.get(url to data);
const data = await res.data
setData(data) //<---this works fine
}catch(error){
console.log(error)
}
}
useEffect(()=>{
getData()
},[])
return(
<div style={pageStyle}>
<Child data={data}/> //<---this sends ok the first time
</div>
)
}
export default Parent
Child Component:
const child = (props) => {
const [data, setData] = useState(props.data || []) //<--first time ok, no data after refresh
const [fields, setFields] = useState([])
const getheaders=(req, res)=>{
let fieldList = []
Object.keys(data[0]).map((field, index)=>(
fieldList.push({field: field}) //<--This works the first time but breaks after because the there is no data
))
setFields(fieldList)
}
useEffect(()=>{
getheaders() //<--works fine on first load, not on refreshes because data is missing
},[])
return (
<div className="ag-theme-quartz" style={{ height: "100%" }}>
<AgGridReact rowData={data} columnDefs={fields} />
</div>
)
}
export default Child
2
Answers
The useState hook does not automatically update the state when the prop changes.
You can see my answer on below question:
https://stackoverflow.com/a/77672312/23012811
From React docs:
You can ask the parent to pass down the new data props by putting props in the dependency array of useEffect like this: