Implementing consistent data across Vue.js components by retrieving it from the API through Mixins

I have a Mixins that retrieves data from the sessionStorage, which is then utilized in all components. The API call to fetch the data is located in the Main component (App.vue), where it fetches and stores the data into sessionStorage.

  beforeCreate() {
    if (!sessionStorage.getItem('constants')) {
       axios.get('/data').then(function(response) {
            sessionStorage.setItem('constants',JSON.stringify(response.data.result));
      });
   },

In the Mixins, I am unable to retrieve data directly from the sessionStorage due to the timing of when Mixins are executed compared to the App.vue Component.

I attempted to include the fetch call within the Mixins, but encountered issues with multiple calls being made even though I had implemented conditionals while fetching data from sessionStorage.

import Vue from 'vue';

const Constants = Vue.mixin({
  data() {
    const constant = JSON.parse(sessionStorage.getItem('constants'));
    return {
      get constantsData() {
        return {
          COUNTRY: constant.COUNTRY,
          STATE: constant.STATE,
        };
      },
    };
  },
});
export default Constants;

What is the most effective approach for utilizing Mixins with API data?

Answer №1

If you want to retrieve data before creating a component, you can use the following code:

   beforeCreate() {
        if (!sessionStorage.getItem('constants')) {
           axios.get('/data').then(function(response) {
                sessionStorage.setItem('constants',JSON.stringify(response.data.result));
                this.constant = response.data.result;
          });
       }

You can also use mixins to define data that can be shared among components:

    import Vue from 'vue';

    const Constants = Vue.mixin({
      data() {
        return {
          constant: {}
        }
      },
    });

   export default Constants;

Alternatively, you can consider using Vuex for better state management and data sharing between components.

Answer №2

After some searching, I discovered the solution by incorporating a method within mixins. This was necessary because I needed to use constants as dropdown values (such as country names or states retrieved from an API). The method should only be called when the dropdown component is initialized.

const Constants = Vue.mixin({
  methods: {
    getConstantData() {
      return JSON.parse(sessionStorage.getItem('constants'));
    },
  },
  data() {
    return {};
  },
});
export default Constants;

Now, the getConstantData method can be utilized in any component to retrieve the data simply by calling getConstantData()

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

A beginner's guide to styling dates using JavaScript and jQuery

I am having trouble setting the date with a specific format. I currently get "17/11/2021" by default, but I would like it to be "Nov 17, 2021". Additionally, I would like to know how to prevent past dates from being selected using this code. Any assistan ...

Guidelines for showcasing validation summary on an ASP.NET webpage with the help of Javascript

My asp.net form contains multiple required fields that need validation. I am looking to display a summary of all validations at the end of the form. Valid input controls have already been checked, now I just need the summary. Here is an example code s ...

React-Tooltip trimming

Currently, I am facing a dilemma that requires some resolution. The issue at hand is related to the placement of React-Tooltip within the List element. Whenever it's positioned there, it gets clipped. On the other hand, placing it at the bottom isn&a ...

Issue with passing parameters through AJAX setTimeout causing it to not function as expected

When the user inputs something, a program uses ajax to output something back. This process generally works well, but there is an issue with passing variables as parameters to a remote function from a script. The problem arises when using the setTimeout fu ...

Facebook Like Button AJAX Event Handler

I have multiple like buttons on my webpage and I want to activate a PHP script (using AJAX) when someone clicks "like" or "dislike". I've noticed that clicking "like" triggers both a POST and GET request, while clicking "dislike" only triggers a post ...

Angular: Error when TypeScript object returns an array object value

I have encountered a strange issue where the array value returned as [object Set] when I console log it. It's unclear whether this problem is occurring in the component or the service, but the object values are not being displayed. This issue arises ...

Upload multiple files at once, edit span text, and retitle to files chosen

I need help updating the span text for each file uploader on my page. I want the default "Choose a file..." text to change to the selected filename. Can someone assist me with this? Here is a Js fiddle that I've been working on. This is my HTML mark ...

In Loopback, I have defined two remote methods within a single model, yet only one is accessible through the API explorer

I'm facing a challenge with making 2 remote methods function in the same loopback model. Only one is operational in the api explorer at a time - when I comment out or delete the code for one, the other works seamlessly. Here's my approach: modul ...

Ionic3(ios) restricted from loading local resource

I encountered an issue with my code Not allowed to load local resource: file:///var/mobile/Containers/Data/Application/AB6EABD9-CAAF-4AE5-91F9-D8042B34EA87/tmp/cdv_photo_002.jpg This is the code snippet causing the problem let cameraOptions = { ...

Setting up Firebase in an Angular 6 project without using AngularFire

While working on a project, I initially set up Firebase using AngularFire but found that I didn't need to use many of its functions. Instead, I imported firebase/app in each service and directly used specific functions like firebase.auth() and firebas ...

An issue occurred during compilation with 1 error: The required dependency could not be located

Encountering an issue in a Vue component while attempting to import another JavaScript file located in the services/AuthenticationService directory. Error message: Module not found: Error: Can't resolve '@/services/AuthenticationService'. ...

Angular.js enables the ability to display views from several partials that are loaded dynamically

My goal is to create a view composed of multiple partials that are loaded dynamically based on the content type. While I am new to angular.js, my current approach in the controller involves: $(elem).html(string_with_src); $compile(elem.contents())($scope) ...

Tips for maintaining the reference of a Three.js object after importing it as an .obj file

If you want to learn how to incorporate a .obj file into your scene, the official documentation provides a helpful example that can be found here. const loader = new OBJLoader(); // Load the resource loader.load( // Resource URL 'models/monst ...

When attempting to click on another button, the action does not seem to be working as expected. The button in question has a

Greetings! I have encountered an issue where both of my buttons work perfectly fine individually, but when I attempt to use Button A to click Button B using JavaScript, it doesn't seem to work. I can confirm that Button A functions correctly as the al ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

Vue.js encountered an error: Module not found: Unable to resolve

My goal is to eventually create an open source template, but for now I am practicing with the MEVN stack without using Vue CLI and configuring webpack manually. However, I've encountered an error at this point. ERROR in ./src/app/main.js Module not f ...

Error 404: Postgres and NodeJs API not found (Possible duplicate)

I am new to developing with Node.js and currently working on creating APIs using node, express, and a Postgres database. const {Pool} = require('pg'); //const connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/tu ...

Autocomplete failing to provide a valid response, returning a null value instead

Utilizing an Autocomplete feature for employee search, users can input a name and select from the list of results. However, the current onChange function logs the index value instead of the selected employee's name. Is there a way to pass the employee ...

Retrieve the JSON data by passing the variable name as a string

There are JSON files embedded in the page, like so: <script type="text/javascript" language="javascript" src="json/divaniModerni.json"></script> <script type="text/javascript" language="javascript" src="json/divaniClassici.json"></scr ...

Download an image file directly from an HTTP response in Laravel using Vue, Axios, and Intervention Image

Currently, I am in the process of setting up a media asset database by utilizing Laravel, Vue, Axios, and Intervention image. One of my main objectives is to allow the user to specify their desired image height and width before proceeding with the download ...