TanStackT
TanStack2mo ago
36 replies
slow-yellow

Update multiple values at once in an array

We have this form that exists of an array of entries, for every entry they can update the values within. This works perfect with tanstack from array.
But we have this multi select feature where users can select multiple entries en can update these values at bulk,

this is basically how it works
const form = useAppForm({
  defaultValues: {
    transactions: [{ id: 1, category: 'test' }, {id: 2, category: 'test2'}],
  },
});

const [selected, setSelected] = useState<string[]>([])
const transactions = useStore(form.store, (store) => store.values.transactions);

const selectedTransactions = useMemo(() => transactions.filter((t) => selected.includes(t.id)), [transactions]);
const category = useMemo(
  () =>
    selectedTransactions.every((t) => t.category.key === selectedTransactions[0].category.key)
      ? transactions[0].category.key
      : '',
  [selectedTransactions],
    );

// bulk edit
<FieldGroup>
  <Field>
    <Label>Category</Label>
    <Select
      value={category}
      onValueChange={(e) => {
        for (const id in selected) {
          const index = transactions.findIndex((t) => t.id === id);
          const category = categories.find((c) => c.key === e);
          if (index) form.setFieldValue(`transactions[${index}].category`, (e) => category ?? e);
        }
      }}
    >
      <SelectTrigger className="rounded-none border-0 bg-background">
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {categories.map((c) => (
          <SelectItem value={c.key}>{c.value}</SelectItem>
        ))}
      </SelectContent>
    </Select>
  </Field>
</FieldGroup>

I can update one value like this:
  onValueChange={(e) => {
      const category = categories.find((c) => c.key === e);
      form.setFieldValue(`transactions[${0}].category`, (e) => category ?? e);
  }}


But the first example where i loop over the indexes, React crashed and i cant loop over the transactions anymore
field.state.value.map is not a function
Was this page helpful?