0

Update: How do I get an array (currentSchedule) within an array (response)?

I am trying to get the JSON object in "response" within the JSON code below. For instance, I want to get the title & description in "response", but it is not returning anything for me with the codes that I implemented below.

all.json

{"responseCode":200,
"responseMessage":"Channel Listing",
"response":[{
    "id":395,
    "title":"Title 1",
    "description":"Description 1",
    "currentSchedule":[{"eventId":"123456","title":"Hello Title"]}
    }]
}

App.js

class App extends Component {

constructor(props){
    super(props);
    this.state = {
        items: [],
        isLoaded: false,
    }
}


componentDidMount(){
    fetch('/all.json')
        .then(res => {
            res.json()
            })
        .then(json => {
            this.setState({
                isLoaded: true,
                items: [],
            })
        });
}

render() { 

    var { isLoaded, items } = this.state;

    if(!isLoaded) {
        return <div>Loading...</div>;
    }

    else {
        return (
        <div className="App">
            <ul>
                {items.map(item => (
                    <li key={item.id}>
                        Title: {item.title} | Description: {item.description}
                    </li>
                ))};
            </ul>
        </div>
        );
    }
    
}
}


export default App;

1 Answer 1

1

You need to assign response in your setState to view it, somthing like this

componentDidMount(){
    fetch('/all.json')
        .then(res => res.json())
        .then(json => {
            this.setState({
                isLoaded: true,
                items: json.response,
            })
        }).catch(console.log);
}
Sign up to request clarification or add additional context in comments.

7 Comments

I got this error after setting that Unhandled Rejection (TypeError): Cannot read property 'response' of undefined
I have updated the code, try once. You forgot to return res.json()
can you do a console.log(items) in render after destructuring it and do you see any errors in console?
what if there is another array within "response", how do I retrieve that? For instance if within "response" I have "currentSchedule":[{"eventId":"123456","title":"Hello Title",...]} How do I retrieve the eventId? Thanks in advance!
if you want eventId of the first object in that array then it would be json.response[0].currentSchedule[0].eventId
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.