0

I am cascading data to my components with createContext() in React. In this I have an API call, where I'm fetching two different arrays of objects, mapping over them, and creating a final set of data like:

const [organizationData, setOrganizationData] = useState([
    {
        id: "",
        orgName: "",
        street: "",
        city: ""
    }
])

const organizationFunction = async () => {
    try {
        const data = await axios
        .get(
            API_URL + `organizations/${someUniqueId}`
        )
        .then(res => {
            const masterData = res.data.master
            const contactData = res.data.contact
            const combinedData = masterData.map((item, i) => Object.assign({}, item, contactData[i]))
            setOrganizationData(combinedData)
        })
        setOrgLoading(true)
    } catch (e) {
        alert(e)
    }
}

Then I send the data to children

<AuthContext.Provider organizationData={organizationData}>
    {children}
</AuthContext.Provider>

Now, when I try to access this data from one of the children, specifically to populate the inputs of a form with the data from the database, with the help of useEffect when the component is mount, it crashes because in the beginning organizationData is undefined, just the empty object I have defined upfront, so it tries to read organizationData.orgName and breaks with Cannot read property 'orgName' of undefined.

If I console.log(organizationData) in the Context component, the output is

[{…}]
0: {id: "", orgName: "", street: "", city: ""}

(1) [{…}]
0: {id: 12, orgName: "MyOrganization", street: "Skalitzerstr. 31", city: "Berlin"}

So the first output is empty and then the state updates.

I have tried to short circuit when adding data to my form in my child component but that is not working, it still crashes with Cannot read property 'orgName' of undefined.

useEffect(() => {
    setFillingData({
      ...fillingData,
      orgName: organizationData.orgName || "",
      ...
  })
}

Any idea what exactly is wrong here, and how can I avoid exporting organizationData before the state was updated and the data/object created?

Thanks!

labilouser
  • 177
  • 1
  • 2
  • 9

1 Answers1

0

You can add organizationData in dependency array of useEffect

useEffect(() => {
  if(organizationData){
    setFillingData({
      ...fillingData,
      orgName: organizationData.orgName || "",
      ...
   })
  }
}, [organizationData])
Niharika
  • 36
  • 1