skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. From React docs:

    Props are immutable—a term from computer science meaning
    “unchangeable”. When a component needs to change its props (for
    example, in response to a user interaction or new data), it will have
    to “ask” its parent component to pass it different props—a new object!
    Its old props will then be cast aside, and eventually the JavaScript
    engine will reclaim the memory taken by them.

    You can ask the parent to pass down the new data props by putting props in the dependency array of useEffect like this:

    useEffect(()=>{
      getheaders() 
    },[props])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search