Is there a way to refresh my list following a POST request when utilizing a separate endpoint?

I'm struggling with updating my list after a POST request. I haven't been able to find any solutions online. Typically, I would just push an object into an array, but it seems different in this case.

This function utilizes 2 API endpoints. The first one retrieves the list data, while the weather API uses the data from the first endpoint to fetch information about cities that match their names.

async getPreviousWeather() {
      let endpoint = "/api/";
      let promises = [];
      try {
        const response1 = await axios.get(endpoint);

        this.cities = response1.data;
        for (let i = 0; i < this.cities.length; i++) {
          const response2 = await axios.get(
            `https://api.openweathermap.org/data/2.5/weather?q=${this.cities[i].city_name}&units=metric&appid={API_KEY}`
          );
          this.infos.push(response2.data);
        }
      } catch (error) {
        console.log(error);
      }
    },

Now, this endpoint posts data obtained from the first endpoint. The issue I'm facing is how to update the list upon POST. I'm unsure of how to handle pushing new data or calling this.getPreviousWeather(); as it adds both new and previous data.

async onSubmit() {
   

      let endpoint = "/api/";
      try {
        const response = await axios.post(endpoint, {
          city_name: this.city_query,
        });
        this.city_query = null;
        this.getPreviousWeather();
      } catch (error) {
        console.log(error);
      }
    },
    created() {
    this.getPreviousWeather();
  },

Answer №1

After putting together this solution, I'm uncertain of its effectiveness though it does seem to be functioning.

methods: {
    async onSubmit() {
      let endpoint1 = `https://api.openweathermap.org/data/2.5/weather?q=${this.city_query}&units=metric&appid={API_KEY}`;
      let endpoint2 = "/api/";
      try {
        const response1 = await axios.get(endpoint1);
        const response2 = await axios.post(endpoint2, {
          city_name: this.city_query,
        });
        this.city_query = null;
        if (this.error) {
          this.error = null;
        }
        this.infos.push(response1.data);
      } catch (error) {
        console.log(error);
      }
    },

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

Inquiries regarding scopes, node.js, and express

I struggle with understanding scopes and similar concepts in various programming languages. Currently, I am working on an express application where I take user input, query an arbitrary API, and display the results in the console. To interact with the REST ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

Retrieve a result following an AJAX post request to utilize the obtained value in subsequent code functionalities

Below is the code snippet where an "if" statement is used to check if a query has been executed correctly. If it has, a part of the script is stored in a variable called $output. This variable is then immediately read by the notification script included in ...

The State Hook error "state variable is not defined" arises due to an issue with the state declaration in

function Header() { const [keys, setKeys] = useState([]); //custom addition const first = (e) => { var result = new Map() axios.post('http://localhost:8000/' + query) .then(function(response){ var content ...

What is the best way to control the class name of elements using jQuery in an MVC4 application?

Among the <li> elements, one of them contains the class "current". Determining which <li> is the current one. View below: @{ int k = 10; //the value changes with each request } <ul class="car"> @foreach (var item in modelCoun ...

What is the best way to combine ASP.NET Core version 2.1 with Vue CLI version 3?

My current challenge involves attempting to merge the new Vue CLI 3 with ASP.Net Core web in a new project. I am able to successfully create a blank web project using dotnet new, as well as generate a Hello World template using vue create. However, combi ...

Create an object with an asynchronous function/promise declaration

I have a function that returns an object with different functions that I can use. I want to incorporate promises into these functions for better asynchronous handling. var DATABASE = (function () { var exports = {}; exports.query = function(filter = ...

"Return to previous page" feature

I am having difficulty figuring out how to implement the "go back" function for the page. For instance, I have pages A, B, C, and D. The possible switching between pages is as follows: A -> (B <-> C) -> A or D -> (B <-> C) -> D (where A is the cata ...

Tips for retrieving the user-input value from an HTML text field

Exploring the world of JS, I set out to create a basic calculator after just one week of lessons. However, I hit a roadblock when trying to extract user-input values from my HTML text fields. Here's a snippet of my html: <div class="conta ...

Adding images in ascending order according to the parent div's ID

If I have three different divs with unique IDs on a webpage <div id="product-id-001"></div> <div id="product-id-002"></div> <div id="product-id-003"></div> Is there a way to add image elements based on the ID of each d ...

Once the hidden DIV is revealed, the Youtube video within it begins to load

I currently have a hidden DIV on my website that contains a YouTube clip. My goal is to load the video in the background once the page has fully loaded, so that it's ready to play when the user clicks the button to reveal the DIV. However, at the mo ...

Is using float:right making the jquery slide toggle dropdown div (triggered by hover) appear glitchy?

Utilizing jQuery's slidetoggle and hover functions, I have successfully implemented a dropdown feature in my div. Within this div, there is various information displayed including the date, a note counter, and three buttons. The first two are Tumblr ...

retrieving information from server via ajax to display on chart

I am currently utilizing the jqPlot JavaScript library for generating graphs and charts in one of my applications, which can be found at . Within my application, there are approximately 5-6 pages where I have integrated this library. However, I would like ...

Tips for sending multiple JSON objects using the ajax() method

As of now, I have successfully implemented a $.getJSON() call to fetch a JSON string from a specific URL. Here is the simplified code that is currently functioning well: $.getJSON("myURL",function(data){ var receivedJSON = data; }); The retrieved JSO ...

Is there a way to align my two tables next to each other using CSS?

.page { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .items { float: left; } .secondItem { vertical-align: text-top; float: right; } .page-header table, th, td { border: 1px solid; display: block; background-color: ...

What is the best way to separate a table column into a distinct column at the specified delimiter count?

I successfully wrote code that splits the third column into new columns at the slash delimiter. However, I am struggling to modify it to split at the nth (i.e. 2nd) occurrence. I couldn't find a solution online, so I'm reaching out here for help ...

Ways to reset the selected option when the user chooses a different option using either Jquery or Vanilla JavaScript

I am currently working on a functionality to clear the select option when a different brand is selected. The issue I am facing is that when I choose another brand, the models from the previous selection are not cleared out. For example, if I select BMW, I ...

Executing a JavaScript function without passing arguments does not yield the desired result

Within my JS file, I encountered an issue when trying to call one function from another. Initially, I called the function with no arguments using only its name handleResponse. However, when attempting to add arguments by changing the function signature, I ...

Choosing a radio button based on the stored value within a variable

When transferring a variable (active) from my route to EJS, I initially found it easy to simply display its value: <!-- Active Text Input--> <div class="form-outline mb-4"> <label for="active" class="form-label">Active</label> ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...