Saturday, 4 February 2023

Computed function returns undefined with reactive data?

I am kind of new with Vue 3 and Vue ecosystem entirely and I stuck with sht. Here's the problem.

I have an reactive state that I fill with my form code's here:

const formData = reactive({
      some: '',
      key: '',
      value: '',
      pairs: number,
    });

and I have this object that I need to fill because I change some data for my API here's that code.

const formDataForApi: ComputedRef<FormDataObjectModel> =
      computed(() => ({
        some: formData.some,
        key: alterTheKeyValueFunction(formData.key),
        value: formData.value,
        pair: formatPairData(formData.pair)
      }));

and at the click function I try to send the formDataForApi.value to my api but it's always undefined.

How can I fix this. BTW these are all in setup function but I only return formHandle function.

This is also the component.

<script lang="ts">
import {
  computed,
  ComputedRef,
  defineComponent,
  onMounted,
  reactive,
  watch,
} from "vue";

import { alterTheKeyValueFunction } from 'somewhere'

export default defineComponent({
  name: "SomeComponent",
  setup(_, { emit }) {
    onMounted(async () => {
      await getSthFromAnotherAPI()
    });


    const formatPairData = computed(() => {
      if (!pair.value) return;
      return { pair: formData.pair};
    });

  const formData = reactive({
      some: '',
      key: '',
      value: '',
      pairs: number,
    });
  const formDataForApi: ComputedRef<FormDataObjectModel> =
      computed(() => ({
        some: formData.some,
        key: alterTheKeyValueFunction(formData.key),
        value: formData.value,
        ...formatPairData(formData.pair)
      }));


    const formSubmitHandler = async () => {
      //here the form submitter 
    };

    return {

      formData,
      formSubmitHandler,
    };
  },
});
</script>

alterTheKeyValueFunction it's an util func that takes an object that contains 3 string key value pairs and returns interpolated string.

eg: { abc: "hello:, def: "world }

returns hello world.

on the other hand formatPairData() if the pair is filled in the form it returns that value otherwise it returns nothing so when you submit form you don't send the pair data.



from Computed function returns undefined with reactive data?

No comments:

Post a Comment