Home > Mobile >  Creating new array of object from api call in react js
Creating new array of object from api call in react js

Time:11-18

I'm actually getting data from google calendar API for public holidays and I want to show them in the calendar. For that, I'm first getting the data from google API, and then I'm trying to create a new array of objects that will store the data that I needed from the google API calendar. The issue is I'm able to create a new array of objects but not able to add new objects for whole the data getting from the google calendar API. I try using loop but not work.

My code

let google;

useEffect(() => {
    axios.get('https://www.googleapis.com/calendar/v3/calendars/en.australian#[email protected]/events?key=personalkey')
        .then(res => {
            const data = res.data.items;
            console.log("Google api calendar data", data)

        for (let i = 0; i < data.length; i  ) {

            data.map((item) => {
                google = {
                    "id": item.id,
                    "title": item.summary,
                    "location": "Australia",
                    "start": new Date(moment(item.start.date)),
                    "end": new Date(moment(item.end.date)),
                    "description": item.description,
                    "durationday": 'Fulllday',
                    "sameId": null

                }
            })
        }

        console.log("goggle making array of object inside promise", google)
    })
    .catch(err => { console.log('Google api calendar error', err) })

})

My console enter image description here

Data inside google API for reference

enter image description here

CodePudding user response:

Right now you are looping through the items twice. for loop and map both loop through the array. map is what you want and is used if want to modify an array but it requires that you return each object that you want to place in the new array. You should read about how to use map here array.prototype.map. So I think what you are trying to do is the following:

useEffect(() => {
  axios.get('https://www.googleapis.com/calendar/v3/calendars/en.australian#[email protected]/events?key=personalkey')
    .then(res => {
        const data = res.data.items.map((item) => {
          return {
            "id": item.id,
            "title": item.summary,
            "location": "Australia",
            "start": new Date(moment(item.start.date)),
            "end": new Date(moment(item.end.date)),
            "description": item.description,
            "durationday": 'Fulllday',
            "sameId": null
          }
      })
    console.log("Your new array of modified objects here", data)
  })
  .catch(err => { console.log('Google api calendar error', err) })
}, [])
  • Related