0

I have a vue3 frontend set up with pinia as store, like this:

  export const useShopStore = defineStore(
  "shop",
  () => {
    const state = reactive({
      data: {
        fruits: [],
        owners: [],
      },
    });

    let data_copy = {
      fruits: [],
      owners: [],
    };

    async function fetchData() {
      const URL = `${API_URL}/shops`;

      await axios
        .get(URL)
        .then((res) => {
          state.data = { ...res.data };
          data_copy = { ...res.data };
        })
        .catch((err) => {
          if (err.response) {
            console.log(err.response);
          }
        });
    }

    return { data, data_copy, fetchData };
 },
  {
    persist: true,
  }
);

PROBLEM: NO matter what i tried, the variable data_copy is always a reactive copy of data.state.

GOAL: What i want to achieve is that i fetch the data and assign it a.) to the reactive variable state.data as well as b.) to the NON-reactive variable data_copy

REASON: In the template, i have a checkbox group and a computed property to compare the arrays in state.data with the data object that was originally fetch, data_copy. If the state.data object changed, a button "Update changes" is enabled. Meaning, after fetching the data from the API and assigning the result to data_copy, data_copy should never change.

I also tried Object.assign({}, res.data) instead of the deconstruction syntax, that also did not work.

QUESTION: How can i get a truly constant copy from the fetchData result independent of state.data?

Thanks for you help!

1 Answers1

0

Finally, i tried the following which works:

async function fetchData() {
  const URL = `${API_URL}/shops`;

  await axios
    .get(URL)
    .then((res) => {
      state.data = JSON.parse(JSON.stringify(res.data));
      data_copy = JSON.parse(JSON.stringify(res.data));
    })
    .catch((err) => {
      if (err.response) {
        console.log(err.response);
      }
    });
}

I found the answer here.

  • `JSON` is the most simplistic and inefficient way to clone an object. Also, you don't need to clone it twice, since res.data isn't used anywhere else – Estus Flask Feb 09 '23 at 21:08
  • `const data = JSON.parse(JSON.stringify(res.data)) state.data = data; data_copy = data;`this does not work. @EstusFlask how would you suggest to do it cloning only once? – Lucien Chardon Feb 10 '23 at 08:33
  • I mean `data_copy = JSON.parse(JSON.stringify(res.data)); state.data = res.data` – Estus Flask Feb 10 '23 at 08:37