I'm relatively new to Vue 3 and the entire Vue ecosystem, and I've run into a problem. Here's the issue:
I have a reactive state that I populate with my form code like this:
const formData = reactive({
some: '',
key: '',
value: '',
pairs: number,
});
Additionally, I have this object that I need to fill because I modify some data for my API, here's the relevant code:
const formDataForApi: ComputedRef<FormDataObjectModel> =
computed(() => ({
some: formData.some,
key: alterTheKeyValueFunction(formData.key),
value: formData.value,
pair: formatPairData(formData.pair)
}));
When I try to send the formDataForApi.value to my api on click function, it always turns out to be undefined. How can I resolve this? By the way, all of this is within the setup function but I only return the formHandle function.
This is also part of 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 () => {
//the form submitter goes here
};
return {
formData,
formSubmitHandler,
};
},
});
</script>
The alterTheKeyValueFunction is a utility function that takes an object containing 3 string key-value pairs and returns an interpolated string. For example:
{ abc: "hello", def: "world" }
this would return "hello world".
On the other hand, formatPairData() checks if the pair is filled in the form and returns that value, otherwise it returns nothing so that when you submit the form, the pair data isn't sent.