Retrieving the computed value created from an axios get request in Vue

I am attempting to retrieve the computed value in created for a GET request. I have declared the classroomBackground as a string in my data.


        data() {
            return {
                classroomBackground: '' as string,
            }
        }
    

In the computed value, I am performing calculations and setting the value of classroomBackground.


        computed: {
            background: {
                get(): string {
                    if (condition) {
                        return 'value1';
                    } if (condition) {
                        return "value2";
                    }
                    return ' ';
                },
                set(value:string) {
                    this.background = value;
                    this.classroomBackground = value;
                },
            },
        },
    

I tried to achieve the following within the computed get:


        this.classroomBackground = 'somevalue1'; 
        return this.classroomBackground;
    

I am encountering an eslint error:


        unexpected side effect in "background" computed property
    

In the post method, I am sending the data from the computed value.

methods: {


        async onSaveClickSave() {
            try {
                const settings = {
                    classroomBackground: this.background,
                };

                await axios.post<{ api }>('api');

            } catch (e) {
                handleAxiosError(e);
            }

        }
    

After saving the value, when I attempt to retrieve the data, it does not appear in my input box.


        async created() {
            try {
                const settingsResponse = await axios.get<{ api }>('api');
                const { settings } = settingsResponse.data;
                this.background = settings.classroomBackground;
                //this.classroomBackground = settings.classroomBackground;
            } catch (e) {
                handleAxiosError(e);
            }
        }
    

This is part of my template:


        <div class="d-flex">
            <VTextField
                v-model="background"
            >
            </VTextField>
          </div>
    

This is a partial section of the sandbox link where you can understand more about the computed part. Later, I had to add some conditions based on the value of a dropdown: https://codesandbox.io/s/clever-platform-dyrv7?file=/src/App.vue

While trying to restore the data in computed, I receive this error: upon trying to restore the data, I encounter this error in computed

Error in v-on handler: RangeError: Maximum call stack size exceeded

I aim to store the computed value in a data property and later restore and update it by emptying the entire string retrieved from the database.

How can I access the computed value in created during the GET request? How can this be achieved?

Answer №1

To provide the full code for the component, please ensure that computed.background.get() is correct and does not use any unknown variables like condition.

If you intended to achieve something similar to the following:

    computed: {
       background: {
          get(): string {
            return this.classroomBackground
          },
          set(value:string) {
            this.classroomBackground = value;
          },
        },
    },

for saving and restoring state

    methods: {
        save() {
          window.localStorage.setItem("bg", this.classroomBackground);
        },
        restore() {
          this.classroomBackground = window.localStorage.getItem("bg")
        }
    },
    created() {
        this.resore()
    }

Check out CodeSandbox with computed get and set functions

In your code example, there's another version of computed background:


    computed: {
      background() {
        return `linear-gradient(${this.degree}deg, ${this.colors.join(", ")})`;
      }
    }

This computed function may be difficult to deconstruct back to its original parameters, especially if dealing with complex inputs like "#cccccc". It might be better to treat computed values as read-only or one-way values.

For saving and restoring such computed values, you would need to save and restore all underlying values:


    save() {
      window.localStorage.setItem("bgColors", JSON.stringify(this.colors));
      window.localStorage.setItem("bgDegree", this.degree);
    },
    restore() {
      this.$set(
        this,
        "colors",
        JSON.parse(window.localStorage.getItem("bgColors") || "[]")
      );
      this.degree = parseInt(window.localStorage.getItem("bgDegree"), 10) || 0;
    },
 

View an example on CodeSandBox for handling complex computed values

If you wish to store the entire computed background in a database, you can follow these steps:

 save() {
      window.localStorage.setItem("bgFull", JSON.stringify(this.backgound));
    
    },
 restore() {
      this.storedBackgound  = window.localStorage.getItem("bgFull")
 
    },

However, the recovery process is done to another variable which needs to be used later to compute the background.

computed: {
   background() {
      if(this.colors.length){
         return ...computed from colors...
      }
      if(this.storedBackgound){
         return this.storedBackgound
      }
      //default
   }
}

This is just an example, and how you handle default or restored values may vary.

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

Executing multiple HTTP requests in Angular using the HttpClient

Recently, I came across a concerning issue in my Angular 5 App. It all started with this simple call in my service: interface U{ name:string; } ... constructor(private http : *Http*, private httpC:HttpClient) // Http is deprecated - its a compare test ...

Activate a dropdown menu following the selection of a date on a calendar input using vue.js

What I need to do is have two select fields, one for 'days' and the other for 'hours'. When a day is selected, the user should then be able to choose between two available time slots. If they choose day two, the available time slots sh ...

Angular form input set to disabled mode

Visit this link for code <form class="example-form"> <mat-form-field class="example-full-width"gt; <mat-label></mat-label> <input matInput placeholder="Ex. Pizza" [disabled]="filterVal ...

Is it time to refresh the sibling element when it's selected, or is there

I have recently started working with react and TypeScript, and I am facing some challenges. My current task involves modifying the functionality to display subscriptions and transactions on separate pages instead of together on the same page. I want to sh ...

Navigating through keys within a mapped Type in Typescript

Are there alternative methods for iterating through object keys, transforming values, and ensuring the resulting type maintains the same keys as the input? const env = { KEY_1: "VALUE_1", KEY_2: "ANOTHER_VALUE_2" }; function mapV ...

Insufficient attributes in TypeScript component for React application

Developing with React import {Input} from '@xxx/forms'; <Input label="account Name" name="account"/> Type Definition for input import React, { Ref } from 'react'; import { InputProps as UITKInputProps } from ...

"Converting an array to an object results in an

I'm currently working with VueJs and Vuetify, and I've come across the following code: data() { return { valid: false, sequence: [], test: { name: "", description: "", ani: "", environment: [ ...

Can you explain the distinction between certain assignment assertion and ambient declaration?

When declaring that a field is definitely initialized within a class, what distinguishes the ! (exclamation point, definite assignment assertion) from the declare modifier? The subsequent code triggers an error in strict mode as TypeScript cannot confirm ...

The element within the array object is not properly defined and is causing error messages to be displayed

Whenever I try to use Icons[link.label] in my const, I receive the following error message: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'iconsProps'. No index sig ...

The Vue v-model-bound HTML element is unable to update the Vue instance when a different JavaScript entity binds to it and modifies the data

In my project, I have implemented Vue.js for two-way data binding on a remote control alarm clock. The main code can be found here. You can access the running instance of the server here. While most of the page uses Vue and JavaScript for rendering, I de ...

Assigning values to objects in Vue: setting data properties

I am working with a Vue.js app and attempting to update a value inside an object. Specifically, I want to change the 'name' value when the @change="onfilechangev" event occurs. Is there a way to achieve this, or is it not possible to update an ob ...

When performing the operation number.tofixed in Typescript, it will always return a string value instead of a double datatype as expected from parseFloat

let value = 100 value.toFixed(2) -> "100.00" parseFloat(value.toFixed(2)) -> 100 I am encountering an unexpected result with the double type when input is 100.36, but not with 100.00. Framework: loopback4 ...

Issues arising from using Android Studio in conjunction with Quasar framework

I am currently working with quasar and I attempted to start the project using these commands: quasar build -m capacitor -T android quasar dev -m capacitor -T android Unfortunately, when I entered the first command, I encountered this error: FAILURE: Build ...

Certain CSS styles for components are missing from the current build

After building my Vue/Nuxt app, I noticed that certain component styles are not being applied. In the DEVELOPMENT environment, the styles appear as expected. However, once deployed, they seem to disappear. All other component styles render properly. Dev ...

A property in TypeScript with a type that depends on the value of an object

How can we troubleshoot the error not displaying in Typescript and resolve it effectively? Explore Typescript sandbox. enum Animal { BIRD = 'bird', DOG = 'dog', } interface Smth<T extends Animal = Animal> { id: number; a ...

Angular 8 Observable: Managing User Objects

I recently developed a new service and attempted to call an API method (HTTP GET) to retrieve data, but I'm encountering an issue where not all the data objects from the API GET request are being displayed. angular-component.ts public allUsers$: Obs ...

Solving the problem of cookieParser implementation in NestJS

Greetings! I have a question for you. Currently, I am working on developing a backend using NestJS, a Node.js framework. Everything is functioning smoothly except for some issues when it comes to hosting. I have created a new NestJS project and made some ...

The null error occurs when rendering with React's state array

When I try to call an API that emits JSON, I am encountering an issue. I call the promise API function in componentDidMount, set the state, and then call it in the render method, but it always returns a null error. I need assistance, please. Interface fo ...

How can I implement a progress bar that mimics an exchange platform behind data-table components? [Using Vue and Vuetify]

I am working on a cryptocurrency exchange book simulator and I am trying to implement a progress bar that will be displayed behind the values in a table. https://i.stack.imgur.com/9gVsY.png This is the template for my data-table: < ...

Vue Table with Sorting (Order: Descending)

Hey there! I'm new to working with Vue.js and I'm trying to sort a table from highest to lowest. I installed the vue-sorted-table library, but when I run the code, the data always comes back sorted from lowest to highest. Can anyone lend a hand? ...