1

I am new to the react and I am learning how to HTTP get request using axios. I am referring to a youtube video: https://www.youtube.com/watch?v=NEYrSUM4Umw and following along, but I got an error. I think I have minor error but I can't figure it out.

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

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

        this.state = {
             posts: []
        }
    }


    componentDidMount(){

        axios.get('https://api.particle.io/v1/devices/64646468431646/temperature?access_token=547376a1b2')

        .then(response => {
            console.log(response)
            this.setState({posts: response.data})
        })
        .catch(error => {
            console.log(error)
        }
        )
    }

    render() {
        const { posts } = this.state
        return (
            <div>
                temperature
                {
                    posts.length ?
                    posts.map(post => <div key={post.coreInfo.deviceID}> {post.result} </div>) :
                    null
                }
            </div>
        )
    }
}
export default PostList

When I use postman to get a HTTP request, I get the following response:

{ "cmd": "VarReturn", "name": "temperature", "result": "67.55", "coreInfo": { "last_app": "", "last_heard": "2020-04-05", "connected": true, "last_handshake_at": "2020-04-05", "deviceID": "64646468431646", "product_id": 8 } }

My goal is to display the result: 67.55 in the web application.

Thank you in advance

1 Answer 1

2

If you're only getting a single object as the response from your fetch instead of an array, just wrap it in an array -

this.setState({posts: [response.data]})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.