0
votes

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?

1
Can you update your post to include a console.log of the cpt variable after you put it in state?Shawn Andrews
Just added the console.log() in the fetch() call and in render.Mulli

1 Answers

0
votes

according to your code you initialize cpt: [] (which should rather be an object though) in the constructor and then you make a call to the api and only when the promise is resolved you will modify the state, the thing is it happens after the first render call is done, so you get "cannot access property of NULL/Undefined" for cpt['acf']['entry']['subentry'], though this.state.cpt['title'] will rather return undefined in the render()

Upd: To prevent this, isLoading should have been set as true in the constructor