Storing data from an API response into the localStorage using Vue.js upon clicking

My objective is to save specific data in the browser's localStorage upon clicking a link.

However, the output I receive is either undefined or completely empty.

<li v-for="(category, index) in categories" :key="index">   
    <a href="./currentCategory" @click.prevent="getCategory()"> 
        <img class="category-img" :src="category.strCategoryThumb">    
        <p>{{ category.strCategory }}</p>
    </a>
</li>
data() {
    return {
      categories: []
    }
},
methods: {
    getAllCategories() {
        axios
            .get('https://www.themealdb.com/api/json/v1/1/categories.php')
            .then((response) => {
                console.log(response.data);
                this.categories = response.data.categories;  
            }).catch(error => {
                console.log(error);
                alert("API cannot be reached");
            })
    },
    getCategory() {
        localStorage.setItem('currentCategory', this.category.strCategory );
    }
},

I am utilizing the following API:

I suspect that this.category.strCategory might be incorrect but I'm struggling to determine the correct approach.

I have also attempted using this.categories.strCategory

Answer №1

Attempt to successfully navigate through the category

@click.prevent="getCategory(categorie)

and once completed, store it

getCategory(cat) {
    localStorage.setItem('currentCategory', cat );
}

Answer №2

Got the solution with the help of @Nikola Pavicevic

Needed to include a category in the click event

@click.prevent="getCategory(categorie.strCategory)

and then pass it to the designated function

getCategory(cat) {
        localStorage.setItem('currentCategory', cat);
    }

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

Implementing a JSON query with an onkeyup event listener

My main objective with this code is to trigger a json query request by using a textfield to specify the location. It's essentially a quick search feature that searches for specific content on a different website. For example, if I input www.calsolum/ ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Opencart: The Key to Your Website's Success

Quick question - I have a Java snippet that needs to be added to my OpenCart checkout page before the closing </body> tag. However, I cannot locate the </body> tag in the checkout.tpl file of OpenCart. Can anyone guide me on where to find thi ...

Having trouble initiating an AJAX call in Django and returning values to my form

Seeking assistance to run an AJAX call for a quick calculation in my django view and display the result within a span tag on my HTML page. New to Javascript, struggling with triggering my AJAX call. Below is my HTML and JS code: <input type="text" nam ...

Vuetify: Utilizing condition-based breakpoints

Here is the layout that I am working with: https://i.stack.imgur.com/qlm60.png This is the code snippet that I have implemented: <template> <v-card> <v-card-text> <v-container grid-list-xl fluid class="py-0 m ...

"Utilizing VueJS XHR functionality within a versatile and reusable component

Seeking advice on best practices for improving the following scenario: I have a single global reusable component called <MainMenu>. Within this component, I am making an XHR request to fetch menu items. If I place <MainMenu> in both the heade ...

Tips for utilizing innerHeight for a div during both window loading and resizing tasks?

I'm currently working on calculating the top/bottom padding of a div (.content) based on its height, and updating it upon loading and resizing the window. The goal is to have it centered nicely next to another div (.character) positioned beside it. I ...

Organizing seating arrangements for a concert hall performance

My goal is to develop a custom concert seat booking system using HTML, CSS, and JavaScript. For example, if the concert venue has 10 rows with 20 seats in each row, I could organize them like this: const rows = [ { name: 'A', seats: [1, 2, 3, ...

Invoke ajax to reset session once user navigates away from page

I am looking for a solution to automatically clear the PHP session array every time a user exits my webpage. However, I need to exclude cases where the user clicks on links with query strings. I attempted using Javascript code, but it did not work as expec ...

Instructions for adding a select dropdown feature in Angular 6 that includes a search filter. Additionally, tips on how to filter objects by their name property

I need to add an auto-complete feature in my Angular 6 app where the data is displayed as objects in a dropdown and filtered as we type. **template.html** <mat-form-field > <input matInput [matAutocomplete]="auto" [formControl]="customerFi ...

Function exhibiting varying behavior based on the form from which it is called

Currently, I'm utilizing AJAX to execute a server call, and I've noticed that the behavior of my function varies depending on its origin. Below is an excerpt of the code that's causing confusion: <html> <body> <script> ...

Generating dynamic dropdown lists with JavaScript for variable arrays

I've been scouring the internet for quite some time now, both on this platform and through Google searches, but I can't seem to find what I'm looking for. (Apologies if I missed it and this comes across as a repetitive or annoying question.) ...

JavaScript and HTML with Node.js

Exploring the world of HTML, running smoothly with a static IP address 192.168.56.152 using apache on the host computer. <!DOCTYPE html> <html > <head> <title>OnlinePage</title> <meta charset="utf-8"& ...

Oops! Looks like there's an issue with reading the property 'value' of undefined in React-typeahead

Having some issues with setting the state for user selection in a dropdown menu using the react-bootstrap-typeahead component. Any guidance or resources on this topic would be highly appreciated. Details can be found here. The function handleAddTask is su ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

Utilizing an SSL certification (pem file) within JavaScript

Currently in the process of developing a program to extract data from the FAA's AIDAP database. I received a security certificate in the form of a .p12 file, which I have successfully converted into a .pem file. However, I am encountering difficulties ...

Storing client time data in a database using Node.js

Just starting out with Node.js so bear with me while I learn the ropes. I successfully set up a basic TCP server using the guide here In my current project, users will connect to the server from a web browser and I'm interested in capturing the TCP ...

Error: serialport in node_modules throwing unexpected token SyntaxError

I have been attempting to run the vue-electron app, but I keep encountering this error. App threw an error during load C:\newFolder02\pos4-desktop\node_modules\@serialport\stream\lib\index.js:103 const settings = ...

Show information in a React Native element | Firebase

Just starting out with react native and struggling to display data in a component? You're not alone! I'm having trouble too and would love some guidance on how to destructure the data for display. Any tips? import React,{useState,useEffect} from ...