Skip to content

useForm().post() submits stale data when called immediately after setData() #300

@yorgos-dimitriadis

Description

@yorgos-dimitriadis

When using useForm() in React, calling post() immediately after setData() submits stale/outdated form data, even when using setTimeout with significant delays (tested up to 3 seconds). The post() method appears to capture form data at the time of the function call rather than at execution time.

import { useForm } from '@inertiajs/react';

const { data, setData, post } = useForm({
  code: '',
});

// Scenario: Auto-submit OTP input after 6 digits
<InputOTP
  maxLength={6}
  value={data.code}
  onChange={(value) => {
    setData('code', value);
    
    if (value.length === 6) {
      console.log('Value:', value); // Logs: "123456"
      
      // Attempt 1: Immediate call
      post('/verify-otp');
      // Result: Submits { code: "12345" } ❌
    }
  }}
/>
// Attempt 2: With 3-second delay
onChange={(value) => {
  setData('code', value);
  
  if (value.length === 6) {
    setTimeout(() => {
      post('/verify-otp');
      // Result: Still submits { code: "12345" } ❌
    }, 3000);
  }
}}

Expected Behavior

The post() method should submit the current/updated form data, especially when using setTimeout to delay execution.
Actual Behavior
The post() method submits data from before the last setData() call, even with significant delays. In the example above:

Workaround 1: Use router.post() directly ✅

import { router } from '@inertiajs/react';

onChange={(value) => {
  setData('code', value);
  
  if (value.length === 6) {
    router.post('/verify-otp', {
      code: value // Pass fresh value directly
    });
  }
}}

Workaround 2: Use traditional form submission ✅

<form onSubmit={(e) => {
  e.preventDefault();
  post('/verify-otp'); // Works correctly with button click
}}>
  <InputOTP ... />
  <button type="submit">Verify</button>
</form>

Rails 8.0.3 | InertiaJS 2.2.19

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