[Vuejs]-Computed function returns undefined with reactive data?

1👍

You almost got it, just a few smaller issues:

  • you define formData.pairs (plural) but access it as formData.pair (singular)
  • computed properties are refs, not functions, so formatPairData(formData.pair) does not work
  • when destructuring the computed formatPairData, you need to destructure the ref’s value, not the ref itself, so it should be ....unref(formatPairData)
  • inside the function that builds the computed formatPairData, you access the pair value as pair.value in the if, but it needs to be formData.pair

In the sandbox, this seems to work as expected:

import { computed, defineComponent, reactive, unref } from "vue";

const alterTheKeyValueFunction = (key) => "altered key " + key;

export default defineComponent({
  name: "SomeComponent",
  setup(_, { emit }) {
    const formatPairData = computed(() => {
      if (!formData.pair) return {};  // <--- access as formData.pair
      return { pair: formData.pair };
    });

    const formData = reactive({
      some: "inital some",
      key: "initial key",
      value: "inital value",
      pair: -1, // <---- check "pairs" vs "pair"
    });

    const formDataForApi = computed(() => ({
      some: formData.some,
      key: alterTheKeyValueFunction(formData.key),
      value: formData.value,
      ...unref(formatPairData), // <---- destructure computed ref
    }));

    return {
      formData,
      formDataForApi,
    };
  },
});

Leave a comment