Skip to content
This repository was archived by the owner on Jul 27, 2022. It is now read-only.

(WIP) Fix(useFieldArray): field array in field array not working #712

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mighty-wasps-speak.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-cool-form": patch
---

fix(useFieldArray): nested field array not working
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ const App = () => {

✨ Pretty easy right? React Cool Form is more powerful than you think. Let's [explore it](https://react-cool-form.netlify.app) now!

## Articles / Blog Posts
## Articles / Blog Posts

> 💡 If you have written any blog post or article about React Cool Form, please open a PR to add it here.

Expand Down
97 changes: 83 additions & 14 deletions app/src/Playground/index.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,92 @@
/* eslint-disable no-console */

import { useForm } from "react-cool-form";
import { useForm, useFieldArray } from "react-cool-form";

export default () => {
const { form, runValidation } = useForm({
// validate: () => ({ foo: "Required" }),
focusOnError: ["foo"],
const { form } = useForm({
defaultValues: {
foo: [
{
name: "Iron Man",
arr: [{ name: "iron arr.0" }, { name: "iron arr.1" }],
},
],
},
onSubmit: (values) => console.log("LOG ===> Form data: ", values),
});
const [fields, { push, insert, remove }] = useFieldArray("foo");

return (
<>
<form ref={form} noValidate>
<input name="foo" required />
<input name="bar" required />
{/* <input type="submit" /> */}
</form>
<button type="button" onClick={() => runValidation(["bar"])}>
Validate
</button>
</>
<form ref={form}>
<table>
<thead>
<tr>
<th>Name</th>
<th>Arr</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{fields.map((key, i) => (
<tr key={key}>
<td>
<input name={`foo[${i}].name`} />
</td>
<td>
<Arr field={`foo[${i}]`} />
</td>
<td>
<button type="button" onClick={() => remove(i)}>
REMOVE
</button>
</td>
</tr>
))}
</tbody>
</table>
<div>
<button
type="button"
onClick={() => {
push({ name: "Loki", arr: [{ name: "Your Savior Is Here" }] });
}}
>
PUSH
</button>
<button
type="button"
onClick={() =>
insert(0, {
name: "Spider Man",
arr: [{ name: "Your Friendly Neighborhood Spider-Man" }],
})
}
>
INSERT
</button>
</div>
<input type="submit" />
<input type="reset" />
</form>
);
};

function Arr({ field }: any) {
const [fields, { push }] = useFieldArray(`${field}.arr`);

return (
<div>
{fields.map((key, i) => (
<input
key={key}
style={{ height: "20px", width: "100px" }}
type="text"
name={`${field}.arr[${i}].name`}
/>
))}
<button type="button" onClick={() => push({ name: "xxx" })}>
inner push
</button>
</div>
);
}
2 changes: 1 addition & 1 deletion src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export type Fields = Map<

export type Parsers = ObjMap<Omit<FieldOptions, "validate">>;

export type FieldArray = ObjMap<{ fields: ObjMap; reset: () => void }>;
export type FieldArray = Map<string, { fields: ObjMap; update: () => void }>;

interface EventOptions<V> {
removeField: RemoveField;
Expand Down
69 changes: 40 additions & 29 deletions src/useFieldArray.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";

import {
FieldArrayConfig,
Expand All @@ -18,6 +18,7 @@ import {
compact,
get,
getIsDirty,
getUid,
invariant,
isUndefined,
set,
Expand Down Expand Up @@ -48,15 +49,19 @@ export default <T = any, V extends FormValues = FormValues>(
runValidation,
removeField,
} = methods;
const keysRef = useRef<string[]>([]);

const getFields = useCallback(
(init = false): string[] => {
(init = false) => {
let fields = getState(name);

if (init && isUndefined(fields)) fields = defaultValue;

return Array.isArray(fields)
? fields.map((_, index) => `${name}[${index}]`)
? fields.map((_, index) => {
keysRef.current[index] = keysRef.current[index] || getUid();
return keysRef.current[index];
})
: [];
},
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -65,34 +70,35 @@ export default <T = any, V extends FormValues = FormValues>(

const [fields, setFields] = useState<string[]>(getFields(true));

const updateFields = useCallback(() => {
setFields(getFields());
setNodesOrValues(getState("values"), {
shouldSetValues: false,
fields: Object.keys(fieldArrayRef.current[name].fields),
});
}, [fieldArrayRef, getFields, getState, name, setNodesOrValues]);
useEffect(
() =>
setNodesOrValues(getState("values"), {
shouldSetValues: false,
fields: Object.keys(fieldArrayRef.current.get(name)!.fields),
}),
[fieldArrayRef, fields, getState, name, setNodesOrValues]
);

useEffect(() => {
if (
isUndefined(get(initialStateRef.current.values, name)) &&
!isUndefined(defaultValue)
) {
setDefaultValue(name, defaultValue, true);
updateFields();
setFields(getFields());
}

return () => {
if (shouldRemoveField(name)) removeField(name);
if (shouldRemoveField(name)) removeField(name, ["defaultValue"]);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

if (!fieldArrayRef.current[name])
fieldArrayRef.current[name] = {
reset: updateFields,
if (!fieldArrayRef.current.has(name))
fieldArrayRef.current.set(name, {
update: () => setFields(getFields()),
fields: {},
};
});
if (validate) fieldValidatorsRef.current[name] = validate;

const setState = useCallback(
Expand All @@ -106,8 +112,8 @@ export default <T = any, V extends FormValues = FormValues>(
let state = getState();

(["values", "touched", "errors", "dirty"] as Keys[]).forEach((key) => {
const value = state[key][name];
const fieldsLength = state.values[name]?.length;
const value = get(state[key], name);
const fieldsLength = get(state.values, name)?.length;

if (
key === "values" ||
Expand All @@ -117,32 +123,30 @@ export default <T = any, V extends FormValues = FormValues>(
)
state = set(
state,
key,
{
...state[key],
[name]: handler(
Array.isArray(value) ? [...value] : [],
key,
fieldsLength ? fieldsLength - 1 : 0
),
},
`${key}.${name}`,
handler(
Array.isArray(value) ? [...value] : [],
key,
fieldsLength ? fieldsLength - 1 : 0
),
true
);
});

setStateRef("", { ...state, shouldDirty: getIsDirty(state.dirty) });
updateFields();
setFields(getFields());

if (validateOnChange) runValidation(name);
},
[getState, name, runValidation, setStateRef, updateFields, validateOnChange]
[getFields, getState, name, runValidation, setStateRef, validateOnChange]
);

const push = useCallback<Push<T>>(
(value, { shouldTouched, shouldDirty = true } = {}) => {
const handler: StateHandler = (f, type, lastIndex = 0) => {
if (type === "values") {
f.push(value);
keysRef.current.push(getUid());
} else if (
(type === "touched" && shouldTouched) ||
(type === "dirty" && shouldDirty)
Expand All @@ -163,6 +167,7 @@ export default <T = any, V extends FormValues = FormValues>(
const handler: StateHandler = (f, type) => {
if (type === "values") {
f.splice(index, 0, value);
keysRef.current.splice(index, 0, getUid());
} else if (
(type === "touched" && shouldTouched) ||
(type === "dirty" && shouldDirty)
Expand All @@ -184,6 +189,7 @@ export default <T = any, V extends FormValues = FormValues>(
(index) => {
const handler: StateHandler = (f) => {
f.splice(index, 1);
keysRef.current.splice(index, 1);
return compact(f).length ? f : [];
};
const value = (getState(name) || [])[index];
Expand All @@ -199,6 +205,10 @@ export default <T = any, V extends FormValues = FormValues>(
(indexA, indexB) => {
const handler: StateHandler = (f) => {
[f[indexA], f[indexB]] = [f[indexB], f[indexA]];
[keysRef.current[indexA], keysRef.current[indexB]] = [
keysRef.current[indexB],
keysRef.current[indexA],
];
return f;
};

Expand All @@ -211,6 +221,7 @@ export default <T = any, V extends FormValues = FormValues>(
(from, to) => {
const handler: StateHandler = (f) => {
f.splice(to, 0, f.splice(from, 1)[0]);
keysRef.current.splice(to, 0, f.splice(from, 1)[0]);
return f;
};

Expand Down
17 changes: 8 additions & 9 deletions src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export default <V extends FormValues = FormValues>({
const formRef = useRef<HTMLElement>();
const fieldsRef = useRef<Fields>(new Map());
const fieldParsersRef = useRef<Parsers>({});
const fieldArrayRef = useRef<FieldArray>({});
const fieldArrayRef = useRef<FieldArray>(new Map());
const controlsRef = useRef<ObjMap>({});
const formValidatorRef = useLatest(validate);
const fieldValidatorsRef = useRef<ObjMap<FieldValidator<V>>>({});
Expand Down Expand Up @@ -183,7 +183,7 @@ export default <V extends FormValues = FormValues>({
const fieldArrayName = isFieldArray(fieldArrayRef.current, name);

if (fieldArrayName)
fieldArrayRef.current[fieldArrayName].fields[name] = true;
fieldArrayRef.current.get(fieldArrayName)!.fields[name] = true;

acc.set(name, {
...acc.get(name),
Expand Down Expand Up @@ -389,7 +389,7 @@ export default <V extends FormValues = FormValues>({
}, [builtInValidationMode, runBuiltInValidation]);

const runFieldValidation = useCallback(
async (name: string): Promise<any> => {
async (name: string) => {
const value = get(stateRef.current.values, name);

if (!fieldValidatorsRef.current[name] || isUndefined(value))
Expand Down Expand Up @@ -704,7 +704,7 @@ export default <V extends FormValues = FormValues>({
setNodeValue(name, value);

isFieldArray(fieldArrayRef.current, name, (key) =>
fieldArrayRef.current[key].reset()
fieldArrayRef.current.get(key)!.update()
);

if (shouldTouched) setTouched(name, true, { shouldValidate: false });
Expand Down Expand Up @@ -774,7 +774,7 @@ export default <V extends FormValues = FormValues>({
setStateRef("", state);
onResetRef.current(state.values, getOptions(), e);

Object.values(fieldArrayRef.current).forEach((field) => field.reset());
fieldArrayRef.current.forEach((field) => field.update());
},
[getOptions, onResetRef, setNodesOrValues, setStateRef, stateRef]
);
Expand Down Expand Up @@ -842,8 +842,8 @@ export default <V extends FormValues = FormValues>({
? removeOnUnmounted
: [
...Array.from(fieldsRef.current.keys()),
...Array.from(fieldArrayRef.current.keys()),
...Object.keys(controlsRef.current),
...Object.keys(fieldArrayRef.current),
];
names = isFunction(removeOnUnmounted) ? removeOnUnmounted(names) : names;

Expand Down Expand Up @@ -882,10 +882,9 @@ export default <V extends FormValues = FormValues>({

delete fieldParsersRef.current[name];
delete fieldValidatorsRef.current[name];
delete fieldArrayRef.current[name];
delete controlsRef.current[name];

if (fieldsRef.current.has(name)) fieldsRef.current.delete(name);
fieldArrayRef.current.delete(name);
fieldsRef.current.delete(name);
},
[handleUnset, stateRef]
);
Expand Down
9 changes: 9 additions & 0 deletions src/utils/getUid.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import getUid from "./getUid";

describe("getUid", () => {
it("should work correctly", () => {
// @ts-expect-error
window.crypto = { getRandomValues: () => new Array(16).fill(0) };
expect(getUid()).toBe("00000000-0000-4000-8000-000000000000");
});
});
Loading