Tips for dynamically retrieving data from an API to adapt to the changing API URL prior to page loading (handling empty value issue)

As a newcomer to javascript and vue, I am delving into dynamic routes and attempting to pass data from my local API (Graphql via Apollo) to the Openweathermap API URL upon page load. However, I am facing an issue where the openweather API returns a 400 error because the URL is being passed an empty value (this.city) unless I manually refresh the page. Unfortunately, even after refreshing, the problem persists intermittently. I am struggling to find a solution on how to retrieve the city name value from my local API before axios or fetch attempts to access any data from the openweather API.

To sum it up: The variable this.city is empty when passed to the axios URL, resulting in a 400 error response from the API unless the page is refreshed (which is not always effective).

Here is a snippet of my code:

<script>
  import venueQuery from '~/apollo/queries/venue/venue'


  export default {
    data() {
      return {
        loading: 0,
        venues: [],
        city: '',
        sunset: '',
        currentTemp: ''
      }

    },

    apollo: {
      $loadingKey: 'loading',
      venues: {
        prefetch: true,
        query: venueQuery,

        variables() {
          return {
            slug: this.$route.params.slug
          }
        },
        result(result) {
          return this.city = result.data.venues[0].temperature

        }
      }
    },

    created() {

      this.getWeatherInfo()

    },

    methods: {
      getWeatherInfo() {
        this.$axios
          .$get(`${process.env.WEATHER_BASEAPI}${this.city}${process.env.WEATHER_KEY}`).then(data => {
            this.currentTemp = Math.floor(data.main.temp - 273.15);
            this.sunset = new Date(data.sys.sunset * 1000).toLocaleTimeString("en-GB").slice(0, 5)
          })
      }
    }
  }

</script>

I would greatly appreciate any assistance with this issue.

Answer №1

Because the city data is populated asynchronously after the component is initialized, calling getWeatherInfo() in the created hook would happen before the city data is actually set.

To resolve this issue, you can create a watcher on the city property that will trigger getWeatherInfo() each time there is an update:

export default {
  watch: {
    city() {
      this.getWeatherInfo()
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using FB Messenger iOS to verify a third-party app

I am in the process of creating a web application that features Facebook authentication and the capability to invite friends through Facebook. While working on this project, I encountered a specific issue that is quite frustrating and I am hoping someone o ...

Change the locale on the current path with a query in Next.js by utilizing the router

Managing locale changes centrally can be tricky. When a user selects a new locale from a list, I use useRouter to redirect them to the current page in the selected locale like this: var router = useRouter(); const changeLocale = (selectedLocale) => { ...

What is the most effective way to access a variable from a service in all HTML files of Angular 2/4 components?

In my angular 4 project, I have an alert service where all components can set alerts, but only specific components display them in unique locations. My question is: how can I access a variable from this service across all HTML files? The structure of my s ...

Changing from a vertical to horizontal menu as the parent div is resized

I am looking for a solution to create a CSS effect or Javascript code that will hide a menu inside a div when the browser window or parent div is resized. I want to display another div with the same menu in horizontal orientation when the first one is hidd ...

Vue cookies experiencing issues with updating cookie values correctly

My goal is to store user preferences (maximum 2-3 users) in a cookie for easy access. Upon login, I first check if the 'users' cookie exists. If not, I create it. If it does exist, I check if the current user is included in the cookie. If not, I ...

Creating an object in javascript with two arrays: a step-by-step guide

Looking for help with merging two different object arrays: array1 = [Object, Object, Object] array2 = [Object, Object, Object] Each Object in array1 has the structure: {property1 : "somevalue"} While each Object in array2 follows this structure: {prop ...

Methods for validating React-Router navigation via history.push by utilizing Jest?

What is the best approach to unit test the following function that uses Jest to programmatically direct me to a specified page? function navigateToHome() { history.push('/home'); return { type: 'NAVIGATE_HOME', } } ...

Loading Angular's UI-Router view twice

My Angular application is using Angular UI-Router for routing. Here is the configuration I have set up: var routerApp = angular.module('routerApp', ['ui.router']); routerApp.config(function($stateProvider, $urlRouterProvider) { $urlR ...

Provide solely the specified content range

While working with Node.js, my goal is to develop a video server that can serve a specific portion of a larger media file. Thanks to this gist, I have successfully created a video server and integrated it with an HTML5 video player using: <video contr ...

What is the best way to replace an existing item in an array when adding new data?

My goal is to have a single item in an array that gets updated whenever a new item is clicked. Currently, when I click on an item from a list, it is pushed to the array. However, I want the new item to not only be pushed but also overwrite any previous ite ...

Exploring ways to access an element's background color through JavaScript

Is there a way to access an element's CSS properties that are set by a class name in JavaScript? In the case of the first div element, I have applied a "red" class which sets its background color to red. However, when I try to access the div's b ...

Trouble with variable in require path causing issues with r.js

As a newcomer to optimizing with r.js, I am also a big fan of requirejs build-config.js ({ appDir: "./src/main/webapp/webresources/javascript/", baseUrl: "./", dir: "./target/webresources/js", optimizeCss ...

The attempt to use RTSP streaming with Node.js for an IP camera and JSMPEG

Having an issue connecting to an IP camera where the image does not appear properly When running node app.js "frame= 1970 fps=2.0 q=7.6 size= 22457kB time=00:16:25.00 bitrate= 186.8kbits/s dup=0 drop=3 speed=1.01x" Upon executing index.html &qu ...

JQuery is unable to locate the buttons within the parent div of a reference div

Currently utilizing JQuery version 3.6.1, my objective is to retrieve Buttons 1 & 2 through JQuery. <div class="parent" role="dialog"> <div id="Dialog"/> <div class="buttonPane"> <div cla ...

What could be causing the EBUSY: resource busy or locked, open errno: -4082 error to appear while trying to build storybook 7 in next.js 13?

While attempting to create a storybook, I encountered the following error in my project: [Error: EBUSY: resource busy or locked, open 'C:\Users\ali\Desktop\Works\Design Systems\projects\storybook-test2\node_modu ...

Is there a way to detect and handle errors triggered by a callback function?

My component has the following code snippet: this.loginService.login(this.user, () => { this.router.navigateByUrl('/'); }); Additionally, my service contains this method: login(credentials, callback) { co ...

Having difficulty grasping the concept of toggleClass and jQuery selectors

I am struggling to understand the getLiveSearchUsers function in my JS file. Could someone please help me? I don't quite grasp what selector[0] is and what toggleClass is doing here. $.post("includes/handlers/ajax_search.php", {query:value, userLogge ...

Is it possible to utilize GraphQL with either mongoDB or mySQL databases?

Recently delving into the world of GraphQL, I must say that it is truly an incredible query language that offers vast possibilities. One question that has been lingering in my mind is whether GraphQL can be used with existing databases like mongoDB or my ...

Adding picture to table using JavaScript

I am currently developing a Web application using the Play Framework technology. In one of my scala.html views, I have successfully displayed an image with the following code: <img src="@routes.Assets.at("images/image/1003.png")" width="30" height="30" ...

Creating Elements with Prototype.js and document.createElement()

Hey there, currently delving into the world of prototype.js and noticing some peculiar behavior. Take a look at this code snippet I executed in firebug: var el2 = document.createElement('div'); var k=0; for(var i in el2){ k++}; console.log(k); ...