6

I have a reactive value, which I want to store in a pinia store.

const data = ref({});
async function loadData() {
  fetch("...")
    .then((res) => res.json())
    .then((json) => (data.value = json));
}
loadData();

const myDataStore = useMyDataStore();
const { myData } = storeToRefs(myDataStore);

// Here I want to store data in the store, reactively
myData.value = data.value;

But when I do this, the reactivity is lost. How do you store the value in the store, so that myData is updated every time data is updated?

Codey
  • 1,131
  • 2
  • 15
  • 34

2 Answers2

0

You should define your store like this:

import {defineStore} from 'pinia'

export const useMyDataStore = defineStore('myStore', {
    state: () => ({
        myData: {}
    }),
    actions: {
        update(value){
            Object.assign(this.myData, value);
        }
    }
})

Then use like

const data = ref({});
async function loadData() {
  fetch("...")
    .then((res) => res.json())
    .then((json) => (data.value = json));
}
loadData().then();

const myDataStore = useMyDataStore();

watch(data, (newVal) => {
    myDataStore.update(newVal);
}
Nechoj
  • 1,512
  • 1
  • 8
  • 18
-1

Use watch() to look for changes on your ref data object. On change call the myDataStore.update(newData):

watch(data, (newData) => {
   myDataStore.update(newData)
})

The state in pinia should be updated

Aaron3219
  • 2,168
  • 4
  • 11
  • 28
Lucky_luke
  • 31
  • 2