syncbasestore
Version:
Lightweight reactive store with built-in filtering and async state handling
48 lines (47 loc) • 1.43 kB
JavaScript
import { useSyncExternalStore } from 'react';
export function claimBase(store) {
const state = useSyncExternalStore(store.subscribe.bind(store), () => store.getState());
const getField = (key) => state[key];
const validatedFields = {};
const invalidFields = {};
const warningFields = {};
let hasError = false;
let hasWarning = false;
let allSuccess = true;
for (const key in state) {
const field = state[key];
switch (field.status) {
case 'isError':
hasError = true;
allSuccess = false;
invalidFields[key] = { value: field.value, message: field.message };
break;
case 'isWarning':
hasWarning = true;
allSuccess = false;
warningFields[key] = { value: field.value, message: field.message };
break;
case 'isSuccess':
validatedFields[key] = field.value;
break;
default:
allSuccess = false;
break;
}
}
const formStatus = hasError
? 'isError'
: hasWarning
? 'isWarning'
: allSuccess
? 'isSuccess'
: 'idle';
return {
getField,
full: state,
validatedFields,
invalidFields,
warningFields,
formStatus
};
}