I have a React app that receives an object from WordPress site using fetch() over rest api (v2/posts).
The object contains an "acf" entry which holds ~30 sub entries: some arrays and some are objects. All generated with Advanced Custom Field plugin.
The application is updating this data (using this.state) and the server (fetch/post) upon user request. All is working. I am not using express, redux and the like.
My current problem is that I cannot access the internals of the "acf" entry in render() function, while I can access it within the fetch response. I would like to be able to acccess
cpt['acf']['entry']['subentry']using the entry's names. But I get "cannot access property of undefined..."
Example:
// In constructor: // this.state = { // isLoading: false, title:"", terms:[], cpt: [] // } ... fetch(url) .then(response => { if (response.ok) return response.json() throw new Error('fetchTerm: Something went wrong ...') }) .then(cpt => { var terms = Object.entries(cpt['acf']) var title = Object.values(cpt['title']) this.setState({cpt, terms, title, isLoading: false}) .then( () => { console.log("title",this.state.cpt['title']) console.log("FAMILYLOG",this.state.cpt['acf']['familylog_array']) // shows ok }) return (true) // void - no one is looking... }) //... render(){ if (this.state.isLoading) return (Loading) // occurs only after fetch resturn and this.state variables are instanciated console.log("title", this.state.title) // shows OK console.log("FAIL", this.state.cpt['title']) // cannot access property of NULL/Undefined... console.log("FAMILYLOG",this.state.cpt['acf']['familylog_array']) // same problem }
What am I missing?
I would like to be able to acccess cpt['acf']['entry']['subentry']
Should I regenerate the cpt into arrays/objects in the Component state?