Reactive Object is not updating on template Vue3 Composition API

Viewed 2955

I'm struggling with this for a few days, maybe you could help me. I'm trying to fetch data from firebase (saved in state.state.memory and display it on my template. My variable saved updates on console, but template doesn't shows anything. I tried everything but I can't get anything on the template, could you explain?

Thanks!!

template

<template>
  <div class="memory" id="memory">
    Memory
    <div class="elementos-memoria" v-for="item in saved" :key="item">
      {{ item.primero + item.operador + item.segundo + ' = ' + item.resultado }}
    </div>
    <div class="elementos-memoria" v-for="cuenta in cuentas" :key="cuenta">
      {{ cuenta }}
    </div>
  </div>
</template>

script

import M from "materialize-css";
import { inject, reactive, watch } from "vue";

export default {
  props: {
    cuentas: Array,
  },
  setup() {
    const state = inject("store");
    let saved = reactive({});
    watch(
      () => state.state.memory,
      () => {
        saved = state.state.memory;
        console.log(saved);
      }
    );

    setInterval(() => console.log(saved), 1000);

    return {
      saved,
    };
  },
  mounted() {
    M.AutoInit();
  },
};

Auth.js File

const state = reactive({
    user: {},
    memory: {},
})

const login = (email, password) => {
    let memory = []
    auth.signInWithEmailAndPassword(email, password).then((data) => {
        state.user = data.user
        db.collection('users').doc(state.user.uid).collection('operaciones').get().then((queryResult) => {
            queryResult.forEach(doc => {
                memory.push(doc.data())
            })
            state.memory = memory
        }).catch(err => console.log(err))
    })
}

const signIn = (email, password) => {
    auth.createUserWithEmailAndPassword(email, password).then(cred => {
        state.user = cred.user;
    })
}


const logout = () => {
    auth.signOut().then(() => {
        state.user = null;
        state.memory = null;
    })
}

1 Answers

Looks like you're replacing the reactive state value instead of mutating it

saved = state.state.memory; will replace it.

not sure what's in the state.state.memory object (assuming it is an object), but you can use Object.assign to dynamically update:

if (state.state.memory) {
  Object.assign(saved, state.state.memory)
}
Related