1

I am using Ionic React to create an app that displays temperatures. I have set up an API that sends the MQTT temperature data across and uses Axios to get the data. I am trying to figure out if this is the best way to retrieve the data as I keep getting errors.

The GET API

routes.get('/', (req, res, next) => {
    let parsed = parseInt(test);
    res.status(200).json({ temp: parsed })
})

The Axios & React code

import './ExploreContainer.css';
import React, { Component } from 'react';
import axios from "axios";

interface ContainerProps { }

const sendGetRequest = () => {
    return axios({
        url: `http://localhost:3000/temps`,
        method: 'get'
    }).then(response => {
        console.log(response);
        return response.data;
    })
};

const ExploreContainer: React.FC<ContainerProps> = () => {
    const [items, setItems] = React.useState([]);

    React.useEffect(() => {
        sendGetRequest().then(data => setItems(data.articles));
    }, []);

    return (
    <div className="container">
        {
            items.map(item => {
                return (
                    {item}
                );
            })
        }
    </div>
  );
};

export default ExploreContainer;

The error I get is TypeError: Cannot read property 'map' of undefined I know it has something to do with it expecting an array on the useState() function but if I remove the array it still does not display the temperatures as it. What should I insert into the useState() function to expect the data I am sending or should I modify the way I am sending the temperatures or should I be doing this a different way?

IAmAndy
  • 121
  • 2
  • 12
  • `sendGetRequest().then(res => setItems(res.data.articles));` and (optional, not required to fix the problem) remove `... .then(response => { console.log(response); return response.data; })` Check https://stackoverflow.com/q/14220321/2873538 – Ajeet Shah Mar 06 '21 at 14:54

1 Answers1

1

Just an update! I found out what I did.

sendGetRequest().then(data => setItems(data.temps));

I was trying to access data.articles (When there were no articles object. I had a temp object)

Then on my express route, I needed to enclose my temperatures in an array

routes.get('/', (req, res, next) => {
    let parsed = parseInt(test);
    res.status(200).json({ temps: [parsed] })
})

as react was looking for an array:

const [items, setItems] = React.useState([]);

IAmAndy
  • 121
  • 2
  • 12