diff --git a/src/api/createFormStore.js b/src/api/createFormStore.js index 1a5387e..c283de0 100644 --- a/src/api/createFormStore.js +++ b/src/api/createFormStore.js @@ -2,12 +2,17 @@ import { useState, useEffect } from "react"; import { DISPATCHER_LABEL } from "../utils/constants"; import { noop } from "../utils/noop"; -export function createFormStore() { +export function createFormStore(initialFormState) { const { subscribe, notify } = createListener(); - const stateRef = { current: {} }; - const store = formState => { - stateRef.current = { ...stateRef.current, ...formState }; - notify(stateRef); + const stateRef = { current: { state: { ...initialFormState } } }; + const store = { + update(formState, shouldNotify = true) { + stateRef.current = { ...stateRef.current, ...formState }; + shouldNotify && notify(stateRef); + }, + getState() { + return stateRef.current.state; + } }; return [store, useFieldSelector(subscribe, stateRef)]; } diff --git a/src/hooks/useForm.js b/src/hooks/useForm.js index cd72766..c3b1a3a 100755 --- a/src/hooks/useForm.js +++ b/src/hooks/useForm.js @@ -23,6 +23,7 @@ import { const emptyStateValue = {}; const validatorsDefault = []; +const emptyFormStore = { getState: noop, update: noop }; export function useForm({ initialState, @@ -42,7 +43,7 @@ export function useForm({ _onMultipleForm_, // Private API name, action, - formStore = noop + formStore = emptyFormStore }) { const [formState, dispatch] = useState(() => createForm(initialState, formStore) @@ -69,7 +70,7 @@ export function useForm({ stateRef.current = { ...rest, status, state: newState }; dispatch(stateRef.current); - formStore({ ...stateRef.current, mapFields: mapFields.current }); + formStore.update({ ...stateRef.current, mapFields: mapFields.current }); }, []); const memoInitialState = useRef({ ...formState }); diff --git a/src/utils/formUtils.js b/src/utils/formUtils.js index 106b556..f17a9b5 100644 --- a/src/utils/formUtils.js +++ b/src/utils/formUtils.js @@ -1,8 +1,8 @@ import { STATUS, FORM_VALIDATION_LABEL } from "./constants"; +// eslint-disable-next-line no-unused-vars export const createForm = (state = {}, formStore) => { - formStore({ state, mapFields: {} }); - return { + const formState = { state, isValid: true, status: STATUS.READY, @@ -11,6 +11,8 @@ export const createForm = (state = {}, formStore) => { submitAttempts: 0, submitted: 0 }; + formStore.update(formState, false); + return formState; }; export const getValueByPath = (path, obj, separator = "/") => {