What is the best way to retrieve nested JSON information in React?

I'm encountering difficulties accessing the JSON data retrieved from the Accuweather API in React's Render Method.

Despite seeing the value in the JSON view after opening and formatting the link, I keep getting an 'undefined' error on React. I've attempted to use the dot method without success.

import React, { Component } from 'react';

class App extends Component {

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

componentDidMount() {


fetch('http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln')

.then(res => res.json())  
.then(json => {
    this.setState({
        isLoaded:true, 
        items:json, 
      })
})
}
render() {
var {isLoaded, items} = this.state; 
if (!isLoaded) {
    return <div> Loading...</div>; 
}
else {
  return (
    <div className="App">

     <h1>IES Storm Water Forecast</h1>
     <h1>{new Date().toString()}</h1>
     <h2> Weather Forcast: {items["DailyForecasts"]["Day"]["ShortPhrase"]}</h2>

     <h3>Description: {items.Headline.Text}</h3>
     <h6>Source: Accuweather</h6>
    </div>

);
}

}

}

export default App;

JSON object in there:

I receive the following errors:

Unhandled Rejection (TypeError): Cannot read property 'ShortPhrase' of undefined TypeError: Cannot read property 'ShortPhrase' of undefined

However, I should be receiving a short weather sentence.

Answer №1

The structure of the data that is returned looks like this:

object = {
  WeeklyForecast: [
    {
      Day: {
        WeatherIcon: 6,
        Description: "Mostly cloudy",
        ShortDescription: "Mostly cloudy",
        LongDescription: "Mostly cloudy"
      }
    }
  ]
};

In the WeeklyForecast array, you will need to access the object inside it by using:

items["WeeklyForecast"][0]["Day"]["ShortDescription"]

You can also use dot notation for a shorter way of accessing the same information:

items.WeeklyForecast[0].Day.ShortDescription

Answer №2

To implement a template condition, include the code snippet below: ...

else {
  return (
    <div className="App">

     <h1>IES Storm Water Forecast</h1>
     <h1>{new Date().toString()}</h1>
     <h2> Weather Forcast: {items["DailyForecasts"]["Day"] && items["DailyForecasts"]["Day"]["ShortPhrase"]}</h2>
                            ^^^

     <h3>Description: {items.Headline.Text}</h3>
     <h6>Source: Accuweather</h6>
    </div>

);
}
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Mastering Elasticsearch: A Guide to Efficiently Indexing and Searching Data

IndexResponse response = client.prepareIndex("photo", "album","1") .setSource(jsonBuilder() .startObject() .field("title", "vacation") .field("location", "beach") ...

Display the count of ng-repeat items beyond its scope

Currently, I am looping through a list of nested JSON objects in this manner: <div ng-repeat='item in items'> <ul> <li ng-repeat='specific in item'>{{specific}}</li> </ul> </div> I want to ...

Retrieve the value of an object property within a function

I'm facing a bit of a challenge here and couldn't find a solution. Here's an illustration of the object I am working with: obj = { key1 : {val : "hi", val2 : "pizza"}, key2 : {val : "hello", val2 : "cheese"} ...

Saving the current date and time in PHP and JS to persist even after the browser has been closed

I am currently facing a situation where I can click on an image and it will display a new image. In the previous grid-item, it shows the day and time I clicked on it. What I want to achieve is to have this functionality persist even after closing and reop ...

Retrieving an item from a deeply nested JSON structure

Here is the json response: { "id": "1234567890123456789", "creation_date": 12345678, "event": "WAITING_PAYMENT", "version": "2.0.0", "data": { "product": { "id": 213344, "name": "Product Name", "has_co_production": false ...

Nodemon has encountered an issue: Unable to listen on port 5000. The address is already in use

During the creation of my project with nodejs and express for the backend, everything was running smoothly. However, whenever I made changes to a file, nodemon would encounter an error preventing the server from restarting: Error: listen EADDRINUSE: addre ...

Tips for optimizing your writing productivity with AngularJS ng-route to generate a large volume of pages

I need to add about 100 more pages to my code. Is there a shortcut to avoid writing the "when" statement 100 times? I want to simplify the code. Here is the existing code: var module = angular.module("sampleApp", ['ngRoute']); module.config([&a ...

Tips for retaining CSS modifications applied with jQuery following an AJAX or form submission

Attempting to conceal specific payment options on our Lightspeed Ecommerce website using jQuery within a designated timeframe (from 18:00 to 24:00) solely for residents in the Netherlands. Due to the inability to modify the checkout page file directly, I ...

Struggling to populate a fresh JavaScript array with values submitted from a form

I am currently working on a form to collect Family information that will be used for enrolling in a new benefit plan. My goal is to populate an array with the necessary values for each individual to create the benefit record. While researching, I have only ...

Creating a jQuery function that replaces specific tags or keywords with a link tag

I am looking to implement a feature where I can highlight or replace matching tags/keywords in the main text of an article and convert those matches into clickable links. An example link format is shown below: en/search.aspx?language=en-US&issue=1& ...

I'm a beginner with Angularjs and I attempted to populate multiple JSON values, but unfortunately, it didn't work as expected

<div ng-controller="studentController" ng-repeat = "student in students | unique = 'RollNo' " > <table class="profile-info"> <tr> <th>Enrollment Number</th> <td> ...

Integrate PHP with JavaScript using Ajax to save MySQL data in JavaScript data structures

Been researching a solution to this issue for quite some time, and it seems many others are facing the same problem. However, I haven't come across a satisfactory answer yet. Here's what I'm trying to achieve: I have a basic database named ...

Ensuring rigorous validation for every element within a JSONB array in PostgreSQL

My postgres DB contains a table called master_data_approval_table, with a field approval_value of type Jsonb which has the following structure: https://i.sstatic.net/y2nCf.png We are looking to retrieve only those records where each object in the jsonb a ...

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

Organize chat messages based on date using JavaScript

I came across a similar query, but it didn't resolve my issue. Check this out: How can I group items in an array based on date? My goal is to organize these chat messages by date after fetching them from the database using AJAX. The console displays ...

AngularJS view fails to reflect updates in the model

This issue with Angular has been widely discussed online, but I ask for your patience. I have tried various solutions without success. Here is a simplified version of my code: View: <div ng-hide="{{beHidden}}"></div> Controller: // Set beHi ...

Guide on sending two values from a form using Ajax and the POST method

How can I send two values, A and B, from a form to check.php using Ajax with the POST method? In the code snippet below, I managed to send two input values to check.php and assign them to variables $A and $B. However, I want to accomplish this without ref ...

Bootstrap Table encountering issues when displaying JSON data from Ajax response

I am currently struggling with an unusual issue. I have received a successful JSON response from the server, which I need to display in my Bootstrap Table. However, I am facing difficulty in displaying the JSON data in the Bootstrap Table while using AJAX ...

What are the steps to seamlessly incorporate and set up Node.js into a web application powered by CodeIgniter that is currently hosted on

After successfully deploying my Codeigniter based application to the online server, I now desire to incorporate instant messaging functionality using socket.io. This can be achieved by installing node.js. Can anyone provide guidance on how to install nod ...

What is the reason behind JavaScript's restriction on using double comparison operators?

What is the reason behind javaScript not supporting double comparison? For example, in 64 < str.charCodeAt(i) && str.charCodeAt(i)<=77, why is it not possible to simplify it to 64 < str.charCodeAt(i)<=77? ...