Skip to content

Commit

Permalink
Update states object on each render (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
zoontek authored Feb 28, 2024
1 parent c098afc commit 43ddb14
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 26 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@swan-io/use-form",
"version": "2.0.0-rc.1",
"version": "2.0.0-rc.2",
"license": "MIT",
"description": "A simple, fast and opinionated form library for React & React Native focusing on UX.",
"author": "Mathieu Acthernoene <[email protected]>",
Expand Down
46 changes: 21 additions & 25 deletions src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
MutableRefObject,
SetStateAction,
useEffect,
useLayoutEffect,
useMemo,
useReducer,
useRef,
Expand All @@ -21,9 +20,6 @@ import {
Validity,
} from "./types";

// For server-side rendering / react-native
const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;

export const useForm = <Values extends Required<Values>, ErrorMessage = string>(
config: FormConfig<Values, ErrorMessage>,
): Form<Values, ErrorMessage> => {
Expand All @@ -32,12 +28,10 @@ export const useForm = <Values extends Required<Values>, ErrorMessage = string>(

const [, forceUpdate] = useReducer(() => [], []);
const mounted = useRef(false);
const arg = useRef(config);
const formStatus = useRef<FormStatus>("untouched");

useIsoLayoutEffect(() => {
arg.current = config;
});
const arg = useRef(config);
arg.current = config;

useEffect(() => {
mounted.current = true;
Expand Down Expand Up @@ -370,25 +364,27 @@ export const useForm = <Values extends Required<Values>, ErrorMessage = string>(
};
}, []);

// Lazy initialization
if (!fields.current) {
fields.current = {} as (typeof fields)["current"];

for (const name in arg.current) {
if (Object.prototype.hasOwnProperty.call(arg.current, name)) {
fields.current[name] = {
callbacks: new Set(),
ref: { current: null },
mounted: false,
state: {
value: arg.current[name].initialValue,
talkative: false,
validity: { tag: "unknown" },
},
};
}
const tmp = {} as (typeof fields)["current"];

for (const name in arg.current) {
if (Object.prototype.hasOwnProperty.call(arg.current, name)) {
tmp[name] = fields.current?.[name] ?? {
callbacks: new Set(),
ref: { current: null },
mounted: false,
state: {
value: arg.current[name].initialValue,
talkative: false,
validity: { tag: "unknown" },
},
};
}
}

fields.current = tmp;

// Lazy initialization
if (!field.current) {
const Field: Contract["Field"] = ({ name, children }) => {
const { subscribe, getSnapshot } = useMemo(
() => ({
Expand Down

0 comments on commit 43ddb14

Please sign in to comment.