How can I use JSON data driven from axios.get method?

axios post json body
axios post form data
axios cheat sheet
axios typescript example
axios post react
axios response to json
get data from json array react
axios get json file

I am trying to use map method on the array included in JSON data I got from axios.get method such as 'console.log(data.results)'. when I try to access to the data in side of it, following error occurs:

TypeError: Cannot read property 'result' of undefined. 

When I put 'console.log(data)', however, it logs the json data without any problems. This is the code I wrote and json data in data object.

componentDidMount() {
  axios.get('https://api.nytimes.com/svc/topstories/v2/science.json?api-key=privatekey')
      .then(result=>
            this.setState({jsonData:result})
           )
      .catch(error=> console.log(error))
  }
  
  render() {
    return(
      <div id="cards-wrapper">
       {console.log(this.state.jsonData.data)}
      </div>
    )
  }
<!-- console error-->

{status: "OK", copyright: "Copyright (c) 2019 Company. All Rights Reserved.", section: "science", last_updated: "2019-01-26T15:57:14-05:00", num_results: 28, …}
copyright: "Copyright (c) 2019 Company. All Rights Reserved."
last_updated: "2019-01-26T15:57:14-05:00"
num_results: 28
results: (28) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
section: "science"
status: "OK"
__proto__: Object

You need to ensure that you check if jsonData.results.data has been set or else it'll throw an error since this data isn't available from the start. Remember that your component does not wait till the async request has fulfilled first, so if you are trying to access a property (in this scenario the data) inside the state before it is set, then it will error out. Here's an example below to fix the issue:

class App extends React.Component {
  state = {
    jsonData: null,
  };

  componentDidMount() {
    axios
      .get(
        "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=JoqkiXzZ0GoPgjxFrhHBA42XLzGwAYFq"
      )
      .then(result => this.setState({ jsonData: result }))
      .catch(error => console.log(error));
  }

  render() {
    return (
      <div id="cards-wrapper">
        {this.state.jsonData && this.state.jsonData.data.results.map((article) => (
          <div key={article.short_url}>
            {article.title}
          </div>
        ))}
      </div>
    );
  }
}

Personally, I'd keep the state as flat as possible and would go about setting data like below. This is because there is a lot of useless data that we can just discard like copyright information. Unless you use this information, we don't need to store it in the state as well as the actual data we need to use.

class App extends React.Component {
  state = {
    jsonData: []
  };

  componentDidMount() {
    axios
      .get(
        "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=JoqkiXzZ0GoPgjxFrhHBA42XLzGwAYFq"
      )
      .then(response => this.setState({ jsonData: response.data.results }))
      .catch(error => console.log(error));
  }

  render() {
    return (
      <div id="cards-wrapper">
        {this.state.jsonData.map(article => (
          <div key={article.short_url}>{article.title}</div>
        ))}
      </div>
    );
  }
}

Or if you want to keep all the other data from the response you can use a loading state that controls if the data should be rendered. Notice how we don't render the actual card until the axios request has fulfilled. This will stop the original issue you're running into where you are rendering data that doesn't exist yet.

class App extends React.Component {
  state = {
    jsonData: [],
    loading: true
  };

  componentDidMount() {
    axios
      .get(
        "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=JoqkiXzZ0GoPgjxFrhHBA42XLzGwAYFq"
      )
      .then(response =>
        this.setState({ loading: false, jsonData: response })
      )
      .catch(error => console.log(error));
  }

  render() {
    return this.state.loading ? (
      <div>loading...</div>
    ) : (
      <div id="cards-wrapper">
        {this.state.jsonData.data.results.map(article => (
          <div key={article.short_url}>{article.title}</div>
        ))}
      </div>
    );
  }
}

Consuming REST APIs In React With Fetch And Axios, We can then use the APIs to consume the data on the client-side. using the JavaScript inbuilt fetch() method and Axios which is a promise-based In other to get the JSON body content from the response, we'd have to  The input data for testing can be stored in single or multiple data sources like XLS, XLSX, XML or in JSON files. Here we will see how to manipulate data stored using JSON. Why Data-Driven Testing?

The response returns an array named results, not data so you access it not with:

console.log(this.state.jsonData.data)

but with

console.log(this.state.jsonData.results)

Axios tutorial - GET/POST requests in JavaScript with Axios, Axios is a promise based HTTP client for the browser and Node.js. data - the payload returned from the server; status - the HTTP code returned from the server​; statusText const config = { method: 'get', url: 'http://webcode.me' } node custom_header.js GET / HTTP/1.1 Accept: application/json, text/plain,  If anyone ends up here, I found a solution if you are using create-react-app. Got it working by throwing my db.json file into the Public folder and calling it by:

is it simply a typo? since it cant read result, but its results.

this.state.jsonData.data.results

How to make HTTP requests like a pro with Axios, Why Axios? As with Fetch, Axios is promise-based. Axios will automatically convert the data to JSON and send it as the request body. To handle the result, you can use the then() method like this: axios.get('https://api.github.com/users/​mapbox') .then((response) => { console.log(response.data);  This is due in large part to the design of RESTful endpoints. A GET request is specifically (and exclusively) for retrieving data from a server. As such, the only information that needs to be sent to the server - according to general practice - is the URI of the entity and any result augmenting parameters in the URL (sort, filter, limit, etc.).

How to Display API Data Using Axios with React, Promise based HTTP client for the browser and node.js Using fetch , the response object needs to be parsed to a JSON object: calls a function on our imported object that contains the Axios call; displays Soon, we'll get signed up on RapidAPI and subscribe to the free tier of the Alpha Vantage API. Why JSON over Excel? In most of our tutorials on Data-Driven Testing, we have used Excel – Apache POI.But there is other medium as well to store data into files such as csv, xml, json, text file, etc. Excel is good to manage data and to use but it comes with its own limitations.

Using data in React with the Fetch API and axios, Fetch is a promise-based API which returns a response object. So, we make use of the json() method to get the response object which is stored  In such cases, it is a good idea to render an empty chart initially and then fetch chart data via AJAX request. In this tutorial, we will see how to use different methods of fetching data using jQuery/Axios and then calling updateSeries method of ApexCharts. Sample Data. We will use the sample data from a local JSON file located on the GitHub repo

How to make an Axios GET request, Axios is a Promise-based HTTP client for JavaScript that can be used in Passing a data object as a parameter to the post method is optional; therefore, ​​the  JSON allows us to overcome the cross-domain issue because we can use a method called JSONP that uses a callback function to send the JSON data back to our domain. It’s this capability that makes JSON so incredibly useful, as it opens up a lot of doors that were previously difficult to work around.

Comments
  • This is right answer. the reason was state was empty, so there was nothing to render. after making sure the date to be set before render, it worked. thank you for your help!
  • in the setstate method, yes i used 'result' for local variable name so I think it supposed not to be bothered when i use it from state.
  • Okay but result is just the name you gave the whole response, which is an object not an array. The actual "data" you need is an array named "results" in the response object.
  • I thought it was typo so i double checked, still does not work. thank you for reply :)