Skip to content

Vue: form.setFieldValue doesn't work with async components #2053

@rastuhacode

Description

@rastuhacode

Describe the bug

form.setFieldValue doesn't work if being called before onMounted hook - doesn't set value or throws any errors / warnings of incorrect usage

Your minimal, reproducible example

https://github.com/rastuhacode/tanstack-set-field-bug

Steps to reproduce

You can check the link with full repro, but I will describe steps shortly

  1. Create simple vite+ vue app
  2. Create async form component (it should have top-level await)
    for ex.
<script setup lang="ts">
import { useForm } from "@tanstack/vue-form";

type Data = {
  name: string | null;
};

const defaultValues: Data = {
  name: null,
};

const form = useForm({
  defaultValues,
});

const fetchMock = async (): Promise<Data> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        name: "John Doe",
      });
    }, 1000);
  });
};

const assignName = (response: Data) => {
  console.log(response.name); // logs "John Doe"
  form.setFieldValue("name", response.name);
  console.log(form.useStore((state) => state.values.name).value); // logs null
};

const response = await fetchMock();
assignName(response);
</script>

<template>
  <form>
    <form.Field name="name" v-slot="{ field }">
      <input
        :value="field.state.value"
        @input="
          (event: InputEvent) =>
            field.handleChange((event.target as HTMLInputElement).value)
        "
      />

      {{ field.state.value }}
    </form.Field>
  </form>
</template>
  1. Modify App.vue to use Suspense
<script setup lang="ts">
import TestForm from "./components/TestForm.vue";
</script>

<template>
  <Suspense>
    <TestForm />
  </Suspense>
</template>
  1. Open the website and check console

Expected behavior

I would consider two solutions:

  1. setFieldValue should actually set field value
  2. If first can not be achieved then it would be good forsetFieldValue to throw error or warning in console + have this case documented

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS: macOS 15.7.3
  • Browser: Chrome 145.0.7632.76 (Official Build) (arm64)
  • Node: 22.17.0
  • bun: 1.3.9

TanStack Form adapter

vue-form

TanStack Form version

v1.28.3

TypeScript version

v5.9.3

Additional context

Workaround is to either

  1. make setFieldValue after or in onMounted hook (basically don't use async components)
  2. replace setFieldValue with reset

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions