Save the API response data to LocalStorage when the button is clicked

Is there a way to save data retrieved from an API into localStorage when a button is clicked?

After executing the following code, I would like to store the obtained result:

function getResults(query) {
    fetch(`https://cors-anywhere.herokuapp.com/https://api.openweathermap.org/data/2.5/find?q=${query}&units=metric&APPID=XXXXXX`)
        .then(weather => {
            return weather.json()
        })
        .then(displayResults)
}

function displayResults(weather) {
    console.log(weather)
    let city = document.querySelector('.cityy')
    city.innerHTML = `${weather.list[0].name}`
    let temp = document.querySelector('.current')
    temp.innerHTML = `${weather.list[0].main.temp}`
    let descr = document.querySelector('.description')
    descr.innerHTML = `${weather.list[0].weather[0].description}`
}

Here's my button:

<input class="butt2" type="button" value="+"/>

Answer №1

If you want to store the weather response object in localStorage, you can make some changes to your getResults function. Here's how you can do it:

function getResults(query) {
    fetch(`https://cors-anywhere.herokuapp.com/https://api.openweathermap.org/data/2.5/find?q=${query}&units=metric&APPID=XXXXXX`)
        .then(weather => weather.json())
        .then(weather => {
          localStorage.setItem(weather.list[0].name, JSON.stringify(weather));
          return weather;
        })
        .then(displayResults)
}

To retrieve the stored information later on, you just need to use localStorage.getItem and parse it back into an object:

displayResults(JSON.parse(localStorage.getItem('name of city')));

Update

If you are looking to store only specific information that is displayed on the page when the user clicks the save button, you can follow this approach:

document.querySelector('.butt2').addEventListener('click', function(event) {
  const store = {
    city: document.querySelector('.city').innerHTML,
    temp: document.querySelector('.current').innerHTML,
    description: document.querySelector('.description').innerHTML
  };
  localStorage.setItem('saved-by-user', JSON.stringify(store))
});

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

Customize the MUI (JoyUI) Autocomplete feature in React using react-hook-form to display a unique value instead of the label

Currently, I am in the process of creating a form that includes JoyUI (material) autocomplete and react-hook-form functionality. The array of objects I am using for my options looks like this: [ { label: "Todo", param: "TODO" }, ...

Run a JavaScript function on a webpage loaded through an AJAX response

I need to trigger a function through an AJAX request sent from the server. The function itself is not located on the calling page. Here's an example of what I am trying to achieve: 1. PHP script being called: <script> function execute() { ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

Encountering an issue while attempting to send an image through JavaScript, jQuery, and PHP

I'm currently attempting to upload an image using JavaScript/jQuery, but I am unsure of how to retrieve the image in order to send it to a server (PHP). I have a form containing all the necessary information that I want to save in MySQL, and I use jQu ...

The error code TS2554 is triggered when 5 arguments are passed instead of the expected 3-4

I'm utilizing the gsap plugin to craft a captivating text animation effect. As I reached the last line of code in my 'animation_text_1' function, specifically where it states "TweenMax.staggerFromTo(.....)", an error cropped up which read: ...

the modal body is taking longer than expected to load with ajax

I have a unique modal that I'm filling with dynamic data through an Ajax GET request upon modal load. Interestingly, the data is not fetched or added to the modal body unless I trigger an alert first. The structure of my modal is as follows: <div ...

Revealing and concealing adjacent elements within a specified class

In an attempt to create a carousel that functions by hiding and showing images when the next and previous buttons are clicked, I have organized my images in a table and assigned the li elements a class of 'li'. There are four images in total, wit ...

What is the best way to display multiple values in a single column in a datatable?

This function works effectively in rendering the code: { "data": "assignedTo", "render": function (data) { var btnDetail = "<a href='/Ticket/TicketDetail?ticketI ...

NVDA fails to announce the "dialog" when a Modal is launched

When testing this simple modal example, I noticed that although the role is set to dialog and focus is correctly received on the dialog container when it opens, NVDA fails to announce the word 'dialog' at the beginning. This issue has been report ...

When the child element's "aria-expanded" attribute is set to true, a CSS class should be dynamically

Is there a way to apply a grey background to the first div when the dropdown is open? I've managed to add CSS based on the child elements' aria-expanding attribute, but I'm unsure how to do it for a parent element. Since I am using Vue, I pr ...

Encountering an "Unexpected token '{'" error while attempting to import chart.js is likely due to the import call expecting only one argument

I'm currently working on a node.js app that utilizes chart.js for visualizations. However, I'm running into errors when trying to import and use Chart. To serve chart.js to the client, I used npm to install it and then added the following code: ...

Centering the scrollIntoView feature on mobile devices is presenting challenges with NextJS applications

Description While navigating on mobile browsers, I'm facing a challenge with keeping an element centered as I scroll due to the browser window minimizing. I've experimented with different solutions such as utilizing the react-scroll library and ...

The success function of the Ajax request remains untouched by the response

My ajax call isn't triggering the success:function(resp){ ...} Despite receiving a response status of 200 and a non-null Json response. This is my ajax setup: $.ajax({ url: '/url/', type: 'GET', data: { pass_ ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Vue.js is experiencing an issue with undefined values within computed properties

I have a specific input tag with the model selectedProp: <input type="text" v-model="selectedProp" /> and I need to loop through items in this manner: <div v-for="item of filteredItems">{{item.prop}}</div> Below is the code snippet fo ...

What is the reason behind Q.js promises becoming asynchronous once they have been resolved?

Upon encountering the following code snippet: var deferred = Q.defer(); deferred.resolve(); var a = deferred.promise.then(function() { console.log(1); }); console.log(2); I am puzzled as to why I am seeing 2, then 1 in the console. Although I ...

Ajax request causing bootstrap success message to have shorter visibility

I encountered an issue with my ajax form that retrieves data using the PHP post method. Instead of utilizing the alert function in JavaScript, I decided to use a bootstrap success message. However, there is a problem as the message only appears for less th ...

Encountering SCRIPT1014 and SCRIPT1002 errors within an Angular4 application when using Internet Explorer 11

My Angular 4 application runs perfectly in various browsers. However, when trying to launch it in Internet Explorer version 11, I encounter the following two errors: SCRIPT1014: Invalid character addScript.js (9,1) SCRIPT1002: Syntax error main.bundle.js ...

Storing a collection of images simultaneously in Firebase Storage and saving their URLs in a Firestore document using Firebase v9

I am currently working on a form that requires users to input data in order to generate a detailed city document. Additionally, users must upload multiple photos of the city as part of this process. Once the form is submitted, a new city document is create ...