react-native-community / releases

React Native releases
https://github.com/facebook/react-native/
1.5k stars 405 forks source link

Can not get Nested JSON Object #136

Closed mohamedshuaau closed 5 years ago

mohamedshuaau commented 5 years ago

Hi. I am not sure if this is the right place to ask this But I can not seem to access nested JSON Object. Here is my fetch and setState.


constructor(props) {
        super(props);

        this.state = {
            article: "",
        };

    }

getSingleArticle(){

        const ArticleID = 1001;

        axios.get('http://192.168.100.36/api/read/'+ArticleID)
            .then(response => {

                this.setState({ article: response.data.article });

        })

    }

And here is a simplified version of the JSONresponse

article: {
 "id":3196
  admin: {
     "id":19
    "admin_id":18
    "name":Ben
  }
}

And on my render return I am doing {this.state.article.admin.name} and it gives me Undefined is not an object this.state.article.admin.name. The name does exist as shown above. It is not returning null or anything. I do not understand whats going on here.

MoKhajavi75 commented 5 years ago

You should ask these type of questions in Stack Overflow!

mohamedshuaau commented 5 years ago

SOF didn’t exactly help

hackdie commented 5 years ago

i wonder why

mohamedshuaau commented 5 years ago

@hackdie sarcasm isn’t really going to help. If you have an answer please do share

eshikerya commented 5 years ago

sarcasm is about the type of your question, it sounds like “why sun is shining”. try to console.log(response) before passing it to setState. but this is very basic debugging skills. this is the first thing even beginner dev would think of. and this is the reason of sarcasm

MoKhajavi75 commented 5 years ago

create conditional rendering (maybe by an isLoading: true state. You don't have the this.state.article.admin... at first!) Also, you can use the ternary operator:

{ this.state.article.admin? this.state.article.admin.name : '...' }

Now please close this issue

mohamedshuaau commented 5 years ago

It is loading the above mentioned json. There is no delay and I’ve used ternary operator. With no luck. Like I mentioned, its returning the json as mentioned above. It is loaded with the rest of the response. I’ve already and still am using ternary operator and I’m still getting undefined. I’ve also used a state to wait to fully load and it still seems to return undefined

stnc commented 4 years ago

create conditional rendering (maybe by an isLoading: true state. You don't have the this.state.article.admin... at first!) Also, you can use the ternary operator:

{ this.state.article.admin? this.state.article.admin.name : '...' }

Now please close this issue

nice work

static getDerivedStateFromProps(props, state) {

    return {
        ...state,
        title: props.posts.title ? props.posts.title.rendered : '...'

    }
}