React - Accessing JSON data from URL parameters using fetch

0 votes
119 views
added Mar 13 in React by lcjr First Warrant Officer (11,760 points)

The error you're encountering, "Uncaught TypeError: Cannot read properties of undefined (reading '0')", typically occurs when you're trying to access a property of an undefined value or an array index that doesn't exist.

In your code, the error is likely happening because API_Params is not a JSON object, but rather a string constructed from a URL. You need to fetch data from the URL and parse it as JSON before trying to access its properties.

To fix this issue, you can use fetch or a similar method to fetch the JSON data from the URL and then parse it. Here's how you can modify your code:

// Fetch data from the URL and parse JSON
fetch(API_Params)
  .then(response => response.json())
  .then(jsonData => {
    // Access the keys
    const stateLower = jsonData.property[0].state_s_lower;
    const districtLower = jsonData.property[0].district_s_lower;
    const street = jsonData.property[0].field_prop_street_t;

    // Now you can use these variables as needed
    console.log("State (lowercase):", stateLower);
    console.log("District (lowercase):", districtLower);
    console.log("Street:", street);
    console.log(API_Params);
  })
  .catch(error => console.error('Error fetching data:', error));
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...