reactJS fetch json data from API

I am the new guy in the JS and reactJS.
I want to get info from API to an array. I made API that show all the info from my DB.
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);
      })
  }

Im want to collect all values from "dayCelsius" line into array.
What i need to change in this code ? Thank you 🙂

39 thoughts on “reactJS fetch json data from API”

  1. 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.

    What I have done differently here is just in the for-loop, I have used data[i].dayCelsius instead of jsonData.dayCelsius[i] and I have assigned it to a variable which allows me to assign it to the array we have created using the useState([]) and the ... operator.

    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) => {
            for (var i = 0; i < data.length; i++) {
              let newTemp = data[i].dayCelsius;
              setTemp(prevTemp => [...prevTemp, newTemp]);   
            }
          })
          .catch(err => console.log(err));
      }
    

    I hope it helps you, have a good day 🙂

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

     const tmpArray = jsonData.map(r => r.dayCelsius);
    
    Reply
  3. 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);
          
    
    Reply

Leave a Comment