Search code examples
javascriptreactjsaxiosresponse

How to convert my response.data get from axios to another response?


When I do my response.data, I get something like:  [{…}, {…}]

If I expand it, I can show you:

[
  0: {...},
  1: {...}
]

I want the values and I've tried almost everything, even a for loop, but it brings me an infinite look. Example:

    let spots = [])
    
    const getSpots = async () => {
        const response = await api.get(`spot/freeSpot`, { headers: { Authorization: `Bearer ${accessToken}`},})
        const data = response.data
        for (let i = 0; i < data.length; i++) {
            spots.push(data[i])
        }
    }

Another trying example:

const [spots, setSpots] = useState()

const loadSpots = useCallback(async() => {
        try {
            const response = await api 
            .get(`spot/freeSpot`, { 
                headers: { 
                    Authorization: `Bearer ${accessToken}`, 
                },
            })

            const data = response.data
            for (let i = 0; i < data.length; i++) {
                setSpots(data[i])
            }

        } catch (err) {
            console.log(err)
        }
    }, [])

    loadSpots()

All these examples brought me an infinite loop, I can do it with an array map too, but I could not filter and access only the values.


Solution

  • Reduce to single array:

    const arr= data.reduce((acc,obj)=> acc.concat(Object.entries(obj)),[])
    

    This will be an array of key and value pairs.

    Then change it back to an object:

    const result = Object.fromEntries(arr)