Error occurs while saving data to an array

Utilizing the fetch-jsonp library, I attempted to retrieve data from the darksky API. However, upon fetching the data, I encountered a TypeError when trying to store it.

  constructor(props) {
        super(props);
        this.state = {
          daily: [],
          hourly: [],
          hourlySum: '',
          dailySum: '',
          loading: true,
          error: null
    };
  }

  componentDidMount() {
    if (navigator.geolocation){
      function success(position) {

        var latitude  = position.coords.latitude;
        var longitude = position.coords.longitude;
        var results = fetchJsonp(`https://api.darksky.net/forecast/key/`+latitude+`,`+longitude+`?units=auto`)
        .then(result => {
          this.setState({
            daily: result.daily.data,
            hourly: result.hourly.data,
            hourlySum: result.hourly,
            dailySum: result.daily,
            loading: false,
            error: null
          });
        })/*.catch(err => {
            // Something went wrong. Save the error in state and re-render.
            this.setState({
              loading: false,
              error: err
            });
          });*/
      };
      function error() {
        console.log( 'geolocation error' )
      };
      navigator.geolocation.getCurrentPosition(success.bind(this), error);
    }
  }

The specific error message reads as TypeError: Cannot read property 'data' of undefined, pointing to daily: result.daily.data. Despite defining daily as an array, I am puzzled by this TypeError. For reference, this is the response format.

Prior to using JSONP due to CORS limitations, I successfully implemented similar functionality with Axios.

This was the functioning Axios code:

var _this = this;
    this.serverRequest = axios.get(`https://api.darksky.net/forecast/key/`+latitude+`,`+longitude+`?units=auto`)
    .then(result => {
      _this.setState({
        daily: result.data.daily.data,
        hourly: result.data.hourly.data,
        hourlySum: result.data.hourly,
        dailySum: result.data.daily,
        loading: false,
        error: null
      });
    })

Thank you in advance.

Answer №1

Visit the https://github.com/camsong/fetch-jsonp website for more information:

Perform JSONP requests similar to window.fetch

This means you must use response.json(), just like with fetch.

Here is an example from the linked page:

fetchJsonp('/users.jsonp')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

Before calling setState, add another then() and call response.json()

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

After reaching the conclusion, the code restarts

Any ideas on how to reset this code every 10-20 seconds? I'm struggling to find a solution! I'm new to coding, so any assistance would be greatly appreciated. Here's the code: var items = document.getElementsByClassName('btn-primary n ...

What is the best way to ensure that the texture is properly positioned when replacing textures in gltf format using Three.js?

Trying to dynamically change the texture of a glTF model using the `THREE.TextureLoader`, I successfully changed the color as expected. However, the texture pattern appeared distorted. Exploring web graphics for the first time, I modified a 3D model viewe ...

What is the best way to transfer information from a parsed CSV file into select dropdown boxes?

I utilized JavaScript to parse the CSV file. Here is an example of a CSV: Year,Model,Mileage,Color,Vin,Image 2012,BUICK LACROSSE FWD V6 FFV 4D SEDAN LEATHER,113046,BROWN,1G4GC5E34CF177752,https:imagelink Below is the code used for parsing: $(document). ...

Tips for assigning focus properties inside VueJS components

Within my component child Input: <template> <div class="basic-input-outer" :style="styles"> <p class="paragraph-small">{{ title }}</p> <input ref="name" :type="type" cla ...

Is it possible to combine onmouseover and onmousedown events in a web application?

This particular code functions correctly for the onMouseOver and onMouseOut events, although it seems to encounter issues with the onMouseDown event. Below is the HTML5 and JavaScript code that I have written. Any feedback on where I may be going wrong wou ...

Ways to retrieve interface definition using a variable

I have an interface that organizes various states together export interface ScanFiltersStatePage1 { keywords: SensitiveInfoFileKeywordFilter categories: string[] classifications: string[] fileTypes: string[] infotypes: string[] regulations: str ...

There is an error in the TypeScript code where it is not possible to assign a string or

I'm struggling to resolve a typescript error. Upon checking the console log, I noticed that the regions returned by Set are an array of strings, which aligns perfectly with the region type in my state. Why isn't this setup working as expected? S ...

Issue encountered when submitting form: Error identified as "Unexpected string expression without template curly in string"

As a novice in React.js, I am facing an issue where setState is not functioning properly when submitting a form. Any suggestions on how to resolve this problem? > class Home extends Component{ constructor(props){ > super(props) > ...

Creating a Typescript Function with a Flexibly Typed Return Value

type FuncGenericReturn = <T>() => T; const funcReturnsNumber: FuncGenericReturn = (): number => 1; (Access the Sandbox here to test.) The issue at hand is: We are seeing an error message stating "Type 'number' is not assignable t ...

Change Google Map to a static image for downloading with the help of jQuery

One of the features on my website is a dynamic GoogleMap with markers and MarkerClusterer functionality. I am looking for a way to enable users to download an image of the map view, including all zooming, moving, and marker locations. So far, attempts to ...

How to utilize a Boolean return value in React Class component following a promise fetch operation

Hello, I have a question about a class I am working on in React. When I call Auth.isAuthenticated() from another component, it always returns false, even though the server is returning a 200 response which should set this.authenticated to true. How can I ...

What is the best way to retrieve a specific value in an array object using JavaScript?

I'm working with an array that has the structure shown below: balance = [ {id: 2, is_selected: true}, {id: 4, is_selected: true}, {id: 15, is_selected: false}, {id: 137, is_selected: false}, {id: 30, is_selected: false} ]; Is ther ...

What is the best way to conceal an <i> element when the <a> element is devoid of content?

How can I dynamically hide the second phone icon if the corresponding phone number link is empty? The numbers are retrieved from a Google Sheet using SheetDB and displayed using PODS shortcodes. Check out the following code snippet: <p>Get my fr ...

Tips for parsing server XML responses with JavaScript

I am currently working on a web project and I have reached a point where I need to pass a hard-coded xml file from Java to JavaScript in order to parse it. However, I am facing some difficulties with this process as I am not sure about the exact steps to t ...

Submitting form data using Vue and PHPMailer

I've been encountering an issue with submitting a contact form from a page. After submitting the form, nothing seems to happen. My tech stack includes Vue, Axios, and PHPMailer for handling this functionality. Upon inspecting the network tab, it appea ...

Facing an issue with TypeScript when attempting to import React createElement in a different class

I currently have a file named SEO.tsx which contains a component import React, { Component } from 'react' export default class SEO extends Component { render() { return ( <div>test</div> ); } } Wi ...

Incorporate duration into date using angular

In my Firebase database, I store the following information: Timestamp for the day a record was created in Firebase. Terms entered by the user at the time of creation. For instance, it may look like this: 1439612582756 // converts to: Aug 14, 2015 15 / ...

What is the best way to retrieve the latest date from an array of objects?

I had an array of objects where each object contained startDate, endDate, ownerID, and ownerType. To get the documents, I used the following statement: var yesterdayDate = new Date(); yesterdayDate.setDate(yesterdayDate.getDate() - 1); var next30daysDate ...

Exploring the Wonder of MVC with Ajax Calls Handling Multiple Parameters

I've been struggling to send 2 parameters from the View to the controller using an ajax call. Everything was working fine when I had only one parameter, but as soon as I added another, the function stopped working. Below is the Javascript code with a ...

Embedding JavaScript within an HTML document

Need help with linking HTML files and utilizing JavaScript outputs? I have an .html file displaying a webpage with tabs that I want to link to another .html file. How can I create a link on my page to navigate to the other file? Additionally, in the linked ...