TanStackT
TanStack13mo ago
5 replies
urgent-maroon

form.setFieldValue with field array

I have a form defined like this:

const form = useForm<Partial<Recipe>>({
  defaultValues: {
    name: name ?? "",
    description: description ?? "",
    instructions: instructions ?? "",
    categories: [...(recipe?.categories ?? [])],
    ingredients: [...(recipeIngredients ?? [])],
    steps: [...(recipe?.steps ?? [])],
  },
  onSubmit: async ({ value }) => {
    await onSubmitHandler(value);
  },
});


I am trying to update a field in the ingredients array (stored as a temporary value when editing it, so I can revert to the previous state if the user cancels the edit):


type SingleIngredient = Recipe["ingredients"][number];
const [tempIngredient, setTempIngredient] = useState<SingleIngredient | undefined>(
  undefined,
);

// Rest of component

form.setFieldValue(`ingredients[${index}]`, tempIngredient);


When doing this I get the following TypeScript error:

Argument of type '`ingredients[${number}]`' is not assignable to parameter of type 'PrefixObjectAccessor<Partial<Recipe>, []>'.


Why can't the setFieldValue() detect that is a proper key? Is there a better way to revert the value at the specific index to the previous state?
Was this page helpful?