Skip to content

Commit

Permalink
createFormStore
Browse files Browse the repository at this point in the history
  • Loading branch information
antoniopangallo committed Apr 7, 2024
1 parent 6c88bb9 commit 0db4387
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
15 changes: 10 additions & 5 deletions src/api/createFormStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)];
}
Expand Down
5 changes: 3 additions & 2 deletions src/hooks/useForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {

const emptyStateValue = {};
const validatorsDefault = [];
const emptyFormStore = { getState: noop, update: noop };

export function useForm({
initialState,
Expand All @@ -42,7 +43,7 @@ export function useForm({
_onMultipleForm_, // Private API
name,
action,
formStore = noop
formStore = emptyFormStore
}) {
const [formState, dispatch] = useState(() =>
createForm(initialState, formStore)
Expand All @@ -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 });
Expand Down
6 changes: 4 additions & 2 deletions src/utils/formUtils.js
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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 = "/") => {
Expand Down

0 comments on commit 0db4387

Please sign in to comment.