user17022531
user17022531

Reputation:

How to fetch and map api response data using axios

Sending request to API and get API response in console and that return data will be object .

API RESPONSE:

Refer Here :Json API response

Now how to disply data on webpage using axios. Below code shows how to call API

import React, { Component } from 'react'
import axios from 'axios'

class PostForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
            key: '10-10-21',
            // Where data will be saved.
            data: [],
        }
        console.log(this.state)
    }

    changeHandler = e => {
        this.setState({ [e.target.name]: e.target.value })
    }

    submitHandler = e => {
        e.preventDefault()
        
        axios
        .get(`http://127.0.0.1:8000/hgetall_hash?key=${this.state.key}`)
        .then(response => {
                        // Updating the state to trigger a re-render       
            this.setState({data: response.data});
            console.log(response.data)
        })
        .catch(error => {
            console.log(error)
        })
    }

    render() {
        const { key } = this.state
        
        return (
            <center><div>
                <form onSubmit={this.submitHandler}>
                    <div>
                        <h2> DATE PICKER</h2><br></br>
                        <input
                            type="text"
                            name="key"
                            value={key}
                            onChange={this.changeHandler}
                        />                        
                    </div>
                    <br></br>
                    <button type="submit">Submit</button>
                </form>
            </div></center>
        )
    }
}
export default PostForm

From this code to to store response in variable and map , display data in Grid view.

Upvotes: 1

Views: 784

Answers (1)

The IT gal
The IT gal

Reputation: 215

The response will be stored in the data which you have defined inside this.state.

this.state.data.map((item)=>( {item.time} )) to display is grid you can use display: grid

Upvotes: 1

Related Questions