Is the returned value undefined when using reactive data in a computed function?

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.

Answer №1

You're on the right track, just a few adjustments to make:

  • make sure to access formData.pair instead of formData.pairs
  • remember that computed properties are refs, so use unref(formatPairData) instead of formatPairData(formData.pair)
  • when destructuring the computed property, remember to destructure the value using ....unref(formatPairData)
  • within the function building the computed property, double check you are accessing formData.pair within the if statement

This example in the sandbox demonstrates these changes:

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 {};
      return { pair: formData.pair };
    });

    const formData = reactive({
      some: "initial some",
      key: "initial key",
      value: "initial value",
      pair: -1,
    });

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending a JSON data blob containing various values to an Ext JS panel

I am currently enhancing an element of my application dedicated to managing client information for a business. Initially, I only stored notes within the clients table along with other attributes. However, to improve functionality, I decided to create a sep ...

How can multiple setState calls be safely executed in a React event handler?

I'm facing a challenge with the following code: function App() { // array to store 3 numbers, all initialized to 0 const [counter, setCounter] = React.useState<number[]>([0, 0, 0]); // increments counter[i] by 1 co ...

Nextjs server encountered an issue where it was unable to connect to the localhost

npm run dev > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563239352239247b372626393f38223b3338227b3439393d3f38317b2133347b372626166678677866">[email protected]</a> dev > next dev ▲ Next.js 14.2. ...

Typescript and ts-jest causing issues with aws-sdk-mock not properly mocking

I'm encountering difficulties while implementing the aws-sdk-mock library with Typescript using ts-jest. I've been trying out the sample test provided on the aws-sdk-mock homepage, as displayed below. However, upon executing this test with ts-jes ...

Swapping out numerical value and backslash with Angular

I am encountering an issue with replacing URL parameters in my code. Take a look at the following code snippet: getTitle() { const title = this.router.url.replace(/\D\//g, ''); return title; } However, it seems to only be removin ...

What causes Omit's unusual behavior when indexed keys are present in the type?

Consider this simple scenario: type Alpha = { children: any; size?: string; }; type Beta = Omit<Alpha, 'children'>; // I understand the type of Beta. type Gamma = { [x: string]: any; children: any; size?: string; }; t ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

Pointer lock controls in Three.js enabling shooting in the y-axis direction

I am currently working on a first-person shooter using three.js and pointerlockcontrols. With the following code, I'm able to shoot in any horizontal direction: var direction = new THREE.Vector3( 0, 0, -1 ); var rotation = new THREE.Euler( 0, 0, 0, ...

Utilizing JavaScript Fetch with User Input to Integrate OpenWeather API Retains Previous Data on HTML Page

I have been working with JavaScript Fetch to retrieve data from the OpenWeather API. In my project, I have created a form where users can input the name of a city to view its weather information. However, I am facing an issue where the data from the previo ...

Failure to append an object to the array occurs when submitting an HTML form

I am facing an issue with a form that is supposed to add input values to an array as objects when submitted. However, every time I submit the form, the console briefly shows that there is an array with one object, only for it to disappear. Below is the f ...

Python failed to execute the flash function on a loaded HTML page

I attempted to display an HTML page that contains flash content, but unfortunately it does not seem to be working properly. The loading process seems to go on endlessly. However, the text and image contents are displaying fine. Below is the code snippet I ...

What is the best way to archive data from CMS within Vue3 for quick access?

I have constructed a basic Content Management System using Laravel Nova within a Vue3/Laravel8 app. As a novice, I am utilizing axios.get to retrieve image links and markdown from a database and then assigning it to a reactive state in this manner: <scr ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

Creating a component that fetches asynchronous data and renders it server-side

In the context of server-side rendering (SSR), it is known that only the router component can request async data using the asyncData method. However, I have a main component (which is not the router component) where I also need to fetch some async data for ...

Tips for passing the same prop twice to a Vue component

Is it achievable with Vue to merge classes like this: const someMergedClass = 'otherClass' <Foo class="someClass" :class="someMergedClass" /> When passing a class and :class in Vue, they are merged together. I am aware ...

Exploring the possibilities of JavaScript within the IntelliJ REST client

I've delved into the extensive documentation provided by JetBrains on their HTTP Client and how to incorporate requests using files with a .http extension. The challenge I'm facing involves utilizing a function from a separate .js file within on ...

Sorting Json Data Using Vue

My experience with Vue.js led me to a challenge I can't quite figure out: how to filter specific data in a Json file. Let me provide more context: I have a Json file filled with various electronics products such as computers, mice, keyboards, etc. I w ...

Analyzing a Typescript project using SonarQube Scanner on a Mac OS slave in Jenkins: A step-by-step guide

My current task involves examining a TypeScript project on Jenkins using the SonarQube Scanner plugin on a Mac OS slave. Software: Jenkins (version 2.32.1) SonarQube Scanner for Jenkins plug-in (version 2.5) SonarQube Scanner (version 2.8) SSH slave plu ...

In TypeScript, vertical bars and null are commonly used for type unions

Greetings! I am just starting to learn JavaScript and TypeScript I have a question about the code snippet below What does the pipe symbol (|) signify? Also, why is null = null being used here? let element: HTMLElement | null = null; ...

Oops! Seems like I can't update headers once they have been sent in Node / Express

Currently working on a tutorial from the MEAN Machine book, specifically the chapter on route APIs. If you want to see the complete code, it's available here: https://gist.github.com/leongaban/6db44e513db4ca9e784f The code below shows how to fetch a ...