Tips for activating a responsive object on the DOM using the Nuxt Composition API

After fetching data from the API, I noticed that my reactive form object was not updating on the DOM even though it changed in the console.log() when I refreshed the page.

When the DOM is mounted, I populate my form object, but because it's a reactive object, it needs to be triggered in the right way. Usually, I would use watch to solve this issue, but I'm trying to find a solution without using watch and only relying on the mounted lifecycle hook.

userInformation.vue


<template>
b {{form}} //does not trigger
</template>

<script>

import { getUserInformation } from '@/utils/userInformation';

export default {

setup(){

 const { store, $axios, i18n } = useContext();
 const { userForm } = getUserInformation();

 const form = reactive({
      fullName: '',
      userName: '',
      aboutMe: '',
      photoUrl: '',
    });

 onMounted(() => {
      if (userForm)
         { 
          console.log('userForm',userForm) //data comes and for updated
          fillForm(userInfo.value);  }
    });

//if I use watch here, the form object will update on the DOM, but 
//I believe there's no need to use watch since userForm gets the necessary values in onMounted 

 const fillForm = async data => {
      if (data) {
        form.fullName = data.fullName || '';
        form.userName = data.nick || '';
        form.aboutMe = data.aboutMe || '';
        form.photoUrl = data.photoURL || '';
      }
    }; 

 return {form}

  } 
}

userInformation.js file

In this file, I gather all information about the user and return userForm. I chose to use a composable function here, which works well and provides the necessary information about the user.

import { computed, onMounted, reactive, useContext, watch } from '@nuxtjs/composition-api';

export function getUserInformation() {
  const { store } = useContext();

  const userInfo = computed(() => store.state['profile'].profileData);

  const userForm = reactive({
    fullName: '',
    userName: '',
    aboutMe: '',
    photoUrl: '',
 
  });

  const fillForm = async data => {
    if (data) {
      userForm.fullName = data.fullName || '';
      userForm.userName = data.nick ||  '';
      userForm.aboutMe = data.aboutMe || '';
      userForm.photoUrl = data.photoURL || '';  
    }
  };

  onMounted(async () => {
    if (userInfo.value) await fillForm(userInfo.value);
  });

  watch(userInfo, async info => {
    if (info) await fillForm(info);
  });

  return { userForm };
}


Answer №1

If you want to ensure reactivity, utilize the ref property with userForm.

import { computed, onMounted, ref, useContext, watch } from '@nuxtjs/composition-api';

export function fetchUserDetails() {
  const { store } = useContext();

  const userDetails = computed(() => store.state['profile'].profileData);

  const userForm = ref({
    fullName: '',
    userName: '',
    aboutMe: '',
    photoUrl: '', 
  });

  const populateForm = async data => {
    if (data) {
      userForm.value.fullName = data.fullName || '';
      userForm.value.userName = data.nick ||  '';
      userForm.value.aboutMe = data.aboutMe || '';
      userForm.value.photoUrl = data.photoURL || '';  
    }
  };

  onMounted(async () => {
    if (userDetails.value) await populateForm(userDetails.value);
  });

  watch(userDetails, async info => {
    if (info) await populateForm(info);
  });

  return { userForm };
}

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

Optimizing VueJS applications with browser caching features for faster loading

I've encountered an issue with my VueJS app. After running npm run build, a new set of dist/* files are generated. However, when I upload them to the server (replacing the old build) and try to access the page in the browser, it seems to be loading th ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

I am interested in incorporating pinia state management into my Vue 3 project

I'm currently working on implementing pinia state management in Vue 3, but I've encountered the following error: Module not found: Error: Can't resolve 'src/stores/cart' in 'C:\Users\Ali Haider\theme-project&b ...

Encountering 404 or 502 errors when running multiple vue.js containers in a Kubernetes and Terraform environment

I'm currently facing an issue with my setup involving Ingress, Terraform, NGINX, and Kubernetes. It's serving a vue.js frontend and a .NET Core backend successfully online. However, when I try to add another Vue.JS instance, it fails to redirect ...

Guide to displaying a template using Vue.js

Incorporating jQuery and vuejs version 2.3.4: https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js The code snippet below demonstrates my current setup: // Instantiating Vue. vueVar = new Vue({ el: '#content', ...

Move a v-img and drop it into a different application

I'm facing an issue with making my image draggable in a different application, like how Google or other websites allow you to drag and drop images. For example, when dragging an image from Google onto a Word document, it usually copies the link of the ...

The following error occurred while running the command "php artisan ui vue get": ErrorException - Unable to open stream: File

Trying to set up VueJS for my Laravel project, but encountered an error when running php artisan ui vue: Can someone please advise on how to resolve this issue? Thank you. ErrorException > copy(D:\Code\Hung's Friend\management&bso ...

I am facing an issue where the components are not being displayed by the Vue3 router

For my latest project, I decided to use Vue3. The first project I worked on using components and routers functioned perfectly. However, I have encountered an issue with calling the Header and Router Component in my Home page. It seems to be opening another ...

Stop allowing the firing of the button click event when the Enter key is pressed in

Currently, I am faced with a user interface issue where pressing the enter key in an input field seems to be triggering a click event on a button (probably because it now has focus). Even though the button has a prevent modifier on its click action (<bu ...

When an array object is modified in Vue, it will automatically trigger the get method to validate any

One of the challenges I am facing is related to a button component that has a specific structure: <template> <button class="o-chip border-radius" :class="{ 'background-color-blue': theValue.isSelected, ...

Incorporate style elements dynamically using an array in Vue

My progress bar's width and color are determined by data from an array. The color of the bar changes based on the value of the data - grey if the progress is 0, blue if it's more than 0, and green if it's 100. <div class="card-item" v-fo ...

Ways to solely cache spa.html using networkfirst or ways to set up offline mode with server-side rendering (SSR)

I am facing an issue with my application that has server-side rendering. It seems like the page always displays correctly when there is an internet connection. However, I am unsure how to make Workbox serve spa.html only when there is no network available. ...

What is the best way to bundle a .js file containing code with the export default syntax?

I have a single .js file with the following code: export default (vueInst, obj, events) => { for (const eventName of events) { ... } } An issue has occurred: Error at Function.missingTransform in /node_modules/buble/dist/buble.cjs.js:376:9 T ...

Customize Vuetify theme colors with your own unique color palette

Attempting to override certain classes src/plugins/vuetify.js import Vue from "vue" import Vuetify from "vuetify/lib/framework" Vue.use(Vuetify) export default new Vuetify({ theme: { primary: "#4BB7E8", ...

Handling typeError in Vue.js JavaScript filter for object manipulation

I need to sort an object based on state names (e.g. Berlin, Bayern ...). Below is the API response I received. "states":{ "Bayern":{ "total":13124737, "rs":"09", "va ...

Troubleshooting issue: Displaying input based on selected option not functioning

<custom-select label="Target Type" v-model="targetType" name="targetType" placeholder="Select Target Type" data-test="overall-type-input" :options="targetTypeOptions ...

Exploring the Benefits of Combining Vue.js with Laravel

Being a newcomer to Vue, I decided to try it out in a recent project and quickly understood why it's so popular. Everything was running smoothly until I tested it in IE, where nothing seemed to work at all. Encountering errors like Object doesn' ...

VueJS offers a mixin that is accessible worldwide

I'm looking to create a global mixin that is accessible everywhere, but not automatically inserted into every component. I don't want to use Vue.mixin({...}); Following the guidelines from this source, I have structured my project accordingly. Y ...

Could you offer guidance on incorporating a component into a Vue route?

I am attempting to integrate a vue component called <channel-card></channel-card> into my home route, but I am encountering multiple errors. Main.js const router = new VueRouter({ routes: [ {path: '/home', component: home} ] ...

The Vue method outputs an [object Promise] upon completion

<template> <div> <h1>{{ searchWord(rawString) }}</h1> </div> </template> <script> import axios from 'axios'; export default { methods: { searchWord(rawString) { c ...