Getting .map() not a function when trying to pass JSON to Vue

Viewed 417

I have created a api on my backend and have the result in JSON on http://localhost:5000/result. I figured out that I need a .js file that will handle the api and allow me to use the data in my Vue components. This is the solution I found:

import axios from 'axios';

const url = "http://localhost:5000/result";

class WeatherService {
    static getWeather() {
        return new Promise((resolve, reject) => {
            axios.get(url).then((res) => {
                try {
                    const data = res.data;
                    resolve(
                        data.map(weather => ({
                            ...weather
                        }))
                    );
                } catch (error) {
                    reject(error);
                }
            })
        })
    }
}

export default WeatherService;

My Vue component

<script>
import WeatherService from '../WeatherService';

export default {
  name: 'Result',
  data(){
    return {
      weather: [],
      error: ''
    }
  },
  async created() {
    try {
      this.weather = await WeatherService.getWeather();
    } catch (error) {
      this.error = error.message;
    }
  }
}
</script>

Once I start up both, I get data.map is not a function and am not able to utilize any of the data.

Edit: I'm realizing now that .map() is used on arrays, and I'm trying to use it on JSON data. What would be a comparable solution?

Edit 2: Json data

{
  "coord": {
    "lon": -97.7431,
    "lat": 30.2672
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 82.15,
    "feels_like": 81.23,
    "temp_min": 80.01,
    "temp_max": 84.2,
    "pressure": 1015,
    "humidity": 37
  },
  "visibility": 10000,
  "wind": {
    "speed": 3.44,
    "deg": 0
  },
  "clouds": {
    "all": 1
  },
  "dt": 1614206313,
  "sys": {
    "type": 1,
    "id": 3344,
    "country": "US",
    "sunrise": 1614171738,
    "sunset": 1614212779
  },
  "timezone": -21600,
  "id": 4671654,
  "name": "Austin",
  "cod": 200
}
1 Answers

The data you need doesn't require any mapping, so the Axios callback should just resolve the API response as-is:

class WeatherService {
    static getWeather() {
        return new Promise((resolve, reject) => {
            axios.get(url).then((res) => {
                resolve(res.data);
            })
        })
    }
}

Note that axios.get() already returns a Promise, so you could just return that without wrapping it:

class WeatherService {
    static getWeather() {
        return axios.get(url).then(res => res.data)
    }
}
Related