Ktas
Ktas

Reputation: 63

reactJS fetch json data from API

I am new to JS and reactJS. I want to get info from API to an array. I made API that show all the info from my database. It looks like this:

press here

const [tempNew, setTempNew] = useState([]);
const getAllWeatherCelsius = () => {
    fetch('http://localhost:5000/weather')
      .then(response => {
        return response.json();
      })
      .then((jsonData) => {
        let tmpArray = [];
        for (var i = 0; i < jsonData.length; i++) {
          tmpArray.push(jsonData.dayCelsius[i])   <---- here is the error
        }
        setTempNew(tmpArray);
      })
  }

I want to collect all values from "dayCelsius" line into array.

What do I need to change in this code?

Upvotes: 0

Views: 84

Answers (3)

hersheys17
hersheys17

Reputation: 61

So, what I understand is that you are facing difficulty in just getting the dayCelsius value from the array of objects you fetch from your API.

It is difficult to make out what the problem is as more info about the error is required to see what is going wrong.

What I have done differently here is instead of the for-loop and jsonData.dayCelsius[i], I have used data.map((r,e) => r.dayCelsius).

const [temp, setTemp] = useState([]);
const getAllWeatherCelsius = () => {
    fetch('http://localhost:5000/weather', {
        method: "GET",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
        }
    })
      .then(response => {
        return response.json();
      })
      .then((data) => {
        const tempArray = data.map((r,e) => r.dayCelsius); 
        setTemp(tempArray);
      })
      .catch(err => console.log(err));
  }

I hope it helps you, have a good day :)

Upvotes: 1

alisasani
alisasani

Reputation: 2968

You can use map function to return the dayCelsius value of each element and store them in the tmpArray.

let tmpArray = jsonData.map((el, i) => el.dayCelsius);
      

Upvotes: 2

Raycas
Raycas

Reputation: 161

Can you provide more info about the error? But You can try using the map function like

 const tmpArray = jsonData.map(r => r.dayCelsius);

Upvotes: 2

Related Questions