Skip to content

Commit

Permalink
should add repeated element in a form state
Browse files Browse the repository at this point in the history
  • Loading branch information
LunaTK committed Nov 8, 2023
1 parent e13bfce commit 021c552
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
37 changes: 36 additions & 1 deletion packages/core/src/AutoForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const MockApp: React.FC<MockAppProps> = (props) => {
afterEach(cleanup);

describe("AutoForm", () => {
it("Add map item", async () => {
it("Add repeated item", async () => {
const namespace = protobuf.parse(`
syntax = "proto3";
Expand Down Expand Up @@ -69,4 +69,39 @@ describe("AutoForm", () => {
"repeated element should be added"
).toEqual([{ children: [""] }]);
});

it('Add map item', async () => {
const namespace = protobuf.parse(`
syntax = "proto3";
message Child {
map<string, string> val = 1;
}
message Parent {
repeated Child children = 1;
}
`).root;

const handleSubmit = vi.fn();
const dom = render(
<MockApp
onSubmit={handleSubmit}
namespace={namespace}
messageType="Parent"
>
<button id="submit" />
</MockApp>
);

fireEvent.click(dom.queryByTestId("add-btn")!);
await vi.waitUntil(() => dom.queryByTestId("delete-btn") !== null);
fireEvent.click(dom.container.querySelector("#submit")!);
await waitFor(() => handleSubmit.mock.calls.length === 1);

expect(
handleSubmit.mock.calls[0],
"repeated element with map should work"
).toEqual([{ children: [{ val: {} }] }]);
})
});
11 changes: 8 additions & 3 deletions packages/core/src/protobuf/input/arrayLike/Repeated.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { FieldOptions } from '../../../models';
import { useChildFields } from '../../../hooks';
import { getInitialValue } from '../../conversion/initial';
import ArrayLike from './ArrayLike';
import { useAutoFormCtx } from '../../../context';
import { proto2Form } from '../../conversion';

interface Props {
name: string;
Expand All @@ -21,12 +23,15 @@ const RepeatedInput: React.FC<Props> = ({ field, name, options }) => {
name,
rules: options?.rules,
});
const ctx = useAutoFormCtx();

return (
<ArrayLike
onAdd={() =>
append({ $value: getInitialValue(field, { ignoreArrayLike: true }) })
}
onAdd={() => {
const value = getInitialValue(field, { ignoreArrayLike: true });
const $value = proto2Form(ctx)(value, field.resolvedType, options);
append({ $value });
}}
onRemove={remove}
fields={fields}
render={({ idx }) => (
Expand Down

0 comments on commit 021c552

Please sign in to comment.