The defaultValue of array field cannot be null #736
Send to my agentDescribe the bug#
- claim the 'name' field mode as 'array'
- useForm defaultValues is 'name': null
- it will broken at useField because of "Object.keys(field.state.value)"
Your minimal, reproducible example#
https://tanstack.com/form/latest/docs/framework/react/examples/array
Steps to reproduce#
- claim the 'name' field mode as 'array'
- useForm defaultValues is 'name': null
- it will broken at useField because of "Object.keys(field.state.value)"
Expected behavior#
As a user, I expected it will be ok when I set the defaultValue as null
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
- OS: MacOS
- Browser: Chrome
- Version: latest
TanStack Form adapter#
None
TanStack Form version#
v0.20.3
TypeScript version#
No response
Additional context#
No response
crutchcorn(GitHub profile, opens in a new tab) added labelstype: bug
crutchcorn(GitHub profile, opens in a new tab) added labelshelp wanted
One throwing optional array field example right here: https://stackblitz.com/edit/tanstack-form-92fv9t?file=src%2Findex.tsx
Not sure if this is something i need, but it looks like it could be stepping stone for easier nested fields handling, or form without default values.
crutchcorn(GitHub profile, opens in a new tab) closed this
0.24.1 should include the fix for this.
BTW, you'll run into issues with
pushFieldnext. The suggested fix is in userspace and looks like this:import * as React from 'react'; import { createRoot } from 'react-dom/client'; import { useForm } from '@tanstack/react-form'; function App() { const form = useForm({ defaultValues: { people: null } as { people: Array<{ name: string; age: number }> | null; }, onSubmit({ value }) { alert(JSON.stringify(value)); }, }); return ( <div> <form onSubmit={(e) => { e.preventDefault(); e.stopPropagation(); form.handleSubmit(); }} > <form.Field name="people" mode="array"> {(field) => { return ( <div> {field.state.value?.map((_, i) => { return ( <form.Field key={i} name={`people[${i}].name`}> {(subField) => { return ( <div> <label> <div>Name for person {i}</div> <input value={subField.state.value} onChange={(e) => subField.handleChange(e.target.value) } /> </label> </div> ); }} </form.Field> ); })} <button onClick={() => { if (!field.state.value) { field.setValue([{ name: '', age: 0 }]); return; } field.pushValue({ name: '', age: 0 }); }} type="button" > Add person </button> </div> ); }} </form.Field> <form.Subscribe selector={(state) => [state.canSubmit, state.isSubmitting]} children={([canSubmit, isSubmitting]) => ( <button type="submit" disabled={!canSubmit}> {isSubmitting ? '...' : 'Submit'} </button> )} /> </form> </div> ); } const rootElement = document.getElementById('root')!; createRoot(rootElement).render(<App />);
Sign in to join this conversation.
Hi, I need a minimal reproduction that isn't a link to our examples