Common frontend library of components for web and mobile environmental
Download package from npm:
Import modules you need in your code:
import { useInterval, isNill } from '@appello/common';
Each new functionality must be added to the folder and exported from the root! This is necessary in order to simplify
the import of the necessary functionality:
import { useInterval, isFunction, ... } from '@appello/common';
If you need to create new module, do not forget to add index.ts with exports.
import { useCodeTimer } from '@appello/common';
Ready-made hook for setting a timer when sending SMS again
import { useCodeTimer } from "@appello/common";
const { seconds, isStart, sendCode } = useCodeTimer();
const Component = () => {
return (
<div>
...
{
isStart && (
<span>{seconds}</span>
)
}
<button type="button" onClick={sendCode} />
...
</div>
);
};
Property |
Description |
Type |
Default |
defaultSeconds |
Countdown time in seconds. Optional. |
number |
59 |
Property |
Description |
Type |
seconds |
Amount of time in seconds. |
number |
isStart |
Syntactic sugar. Is the timer running? |
boolean |
sendCode |
Method that starts the timer. |
void |
import { useCombinedRef } from '@appello/common';
Hook for combining refs.
import { useCombinedRef } from '@appello/common';
const Component = () => {
const firstRef = useRef<number>(0);
const secondRef = useRef<number>(0);
const combinedRef = useCombinedRef(firstRef, secondRef);
combinedRef(5);
}
Property |
Description |
Type |
Default |
firstRef |
First ref. |
Ref |
Required |
secondRef |
Second ref. |
Ref |
Required |
Property |
Description |
Type |
combinedRef |
Combined ref. |
Ref |
import { useDebounceCallback } from '@appello/common';
A hook that deal with the debounced function.
import { useDebounceCallback } from '@appello/common';
const Component = () => {
const [value, setValue] = useState(0);
const { debounce } = useDebounceCallback(
() => {
setValue(value + 1);
},
);
return (
<button type="button" onClick={debounce}>
Click
</button>
);
};
Property |
Description |
Type |
Default |
fn |
Callback for the debounce. |
AnyFuction |
Required |
options |
Lodash options |
DebounceOptions |
Optional |
export interface DebounceOptions {
wait?: number;
leading?: boolean;
trailing?: boolean;
maxWait?: number;
}
Property |
Description |
Type |
debounce |
Invoke and pass parameters to fn. |
AnyFuction |
cancel |
Cancel the invocation of currently debounced function. |
() => void |
flush |
Immediately invoke currently debounced function. |
() => void |
import { useDebounceEffect } from '@appello/common';
A effect with debounce
import { useDebounceEffect } from '@appello/common';
const Component = () => {
const [value, setValue] = useState('hello');
const [records, setRecords] = useState<string[]>([]);
useDebounceEffect(
() => {
setRecords((val) => [...val, value]);
},
[value],
);
return (
<>
<input
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Write text"
/>
<ul>
{records.map((record, index) => (
<li key={index}>{record}</li>
))}
</ul>
</>
);
};
Property |
Description |
Type |
Default |
effect |
The effect callback. |
EffectCallback |
Required |
deps |
The dependencies list. |
DependencyList |
undefined |
options |
Config for the debounce behaviors. See the Options section below for details. |
DebounceOptions |
undefined |
export interface DebounceOptions {
wait?: number;
leading?: boolean;
trailing?: boolean;
maxWait?: number;
}
import { useFirstMountState } from '@appello/common';
A hook that returns the first rendering
import { useFirstMountState } from '@appello/common';
const Component = () => {
const isFirstMount = useFirstMountState();
return console.log(isFirstMount)
};
Property |
Description |
Type |
isFirstMount |
Return first render |
bollean |
import { useInterval } from '@appello/common';
A hook that allows you to call a callback function in a time interval
import { useInterval } from '@appello/common';
const Component = () => {
const { start } = useInterval({
fn: () => {
console.log('Privet')
},
});
return (
<button type="button" onClick={start}>
Start timer
</button>
)
};
Property |
Description |
Type |
Default |
fn |
Callback function, a function that will be called with a certain delay. |
EffectCallback |
Required |
delay |
Delay time |
number |
1000 ms |
immediateStart |
Starts immediately. |
bollean |
undefined |
immediateCallFn |
Is it necessary to call a callback immediately before the timer starts. |
bollean |
undefined |
onStop |
A callback that will be called after the timer stops. |
() => void |
undefined |
Property |
Description |
Type |
start |
Function for starting timer |
() => void |
stop |
Function for stopping timer |
() => void |
setState |
Function for switching timer |
(v: bollean) => void |
import { useLatest } from '@appello/common';
A Hook that returns the latest value, effectively avoiding the closure problem.
import { useLatest } from "@appello/common";
const Component = () => {
const [count, setCount] = useState(0);
const latestCountRef = useLatest(count);
useEffect(() => {
const interval = setInterval(() => {
setCount(latestCountRef.current + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<>
<p>count: {count}</p>
</>
);
};
Property |
Description |
Type |
Default |
value |
Function, ref or any type value for get last active value. |
any |
Required |
Property |
Description |
Type |
resultValue |
Latest value. |
any |
import { useManualUpdate } from '@appello/common';
A hook that can be used to manually update a component.
import { useManualUpdate } from '@appello/common';
const Component = () => {
const update = useManualUpdate();
return (
<>
<div>Time: {Date.now()}</div>
<button type="button" onClick={update}>
Update
</button>
</>
);
};
Property |
Description |
Type |
update |
Callback for update component. |
() => void |
import { useMemoCallback } from '@appello/common';
Hooks for persistent functions. In theory, useMemoizedFn can be used instead of useCallback.
In some scenarios, we need to use useCallback to cache a function, but when the second parameter deps changes, the
function will be regenerated, causing the function reference to change.
import { useMemoCallback } from '@appello/common';
const Component = () => {
const [count, setCount] = useState(0);
const memoCallback = useMemoCallback(() => {
message.info(`Current count is ${count}`);
});
return (
<>
<p>count: {count}</p>
<button
type="button"
onClick={() => setCount((v) => v + 1)}
>
Add Count
</button>
<button type="button" onClick={memoCallback}>
Call
</button>
</>
);
};
Property |
Description |
Type |
Default |
callback |
Callback for memorize. |
AnyFunction |
Required |
Property |
Description |
Type |
callback |
Function that require persistence. |
AnyFunction |
import { useMountEffect } from '@appello/common';
A hook that executes a function after the component is mounted.
import { useMountEffect } from '@appello/common';
const Component = () => {
useMountEffect(() => {
console.log("Mount")
})
return (
<span>component</span>
);
};
Property |
Description |
Type |
Default |
callback |
Callback that is called when the component is mounted. |
AnyFunction |
Required |
import { usePrevious } from '@appello/common';
A Hook to return the previous state.
import { usePrevious } from '@appello/common';
const Component = () => {
const [count, setCount] = useState(0);
const previous = usePrevious(count);
return (
<>
<div>counter current value: {count}</div>
<div>counter previous value: {previous}</div>
<button type="button" onClick={() => setCount((c) => c + 1)}>
increase
</button>
<button type="button" onClick={() => setCount((c) => c - 1)}>
decrease
</button>
</>
);
};
Property |
Description |
Type |
Default |
value |
Any value that will be saved. |
any |
Required |
Property |
Description |
Type |
value |
Any value that saved. |
any |
import { useQueryParamsBuilder } from '@appello/common';
A Hook for manager query params with debounce time
import { useQueryParamsBuilder } from '@appello/common';
const Component = () => {
const [getService, { data }] = useAnyRequest();
const { updateQueryParams } = useQueryParamsBuilder({
queryCb: params => getService(params),
defaultParams: {
categoryId,
search: '',
},
});
return (
<></>
);
};
Property |
Description |
Type |
Default |
requestCb |
Any request function |
() => Promise<any> |
Required |
defaultParams |
Any object. |
AnyObject |
Required |
options |
Lodash options |
DebounceOptions |
Optional |
Property |
Description |
Type |
loading |
Loading promise. |
boolean |
queryParams |
Object with query params. |
AnyObject |
setQueryParams |
Set object using dispatch state. |
React.Dispatch<React.SetStateAction<T>> |
updateQueryParams |
Update query params with. |
(params: Partial<T>, withDebounce = false) => void |
reset |
Reset query params object. |
() => void |
import { useSelectOptions } from '@appello/common';
Converts dictionaries for picker to structure:
[
{
value: 1,
label: 'Select 1'
}, {
value: 2,
label: 'Select 2'
}
]
import { useSelectOptions } from '@appello/common';
const Component = () => {
const convertedOptions = useSelectOptions([
{
val: 1,
text: 'Select 1',
},
{
val: 2,
text: 'Select 2',
},
], {
label: 'text',
value: 'val',
})
return (
<span>{JSON.stringify(convertedOptions)}</span>
);
};
Property |
Description |
Type |
Default |
collection |
Collection of objects to be converted. |
AnyObject[] |
Required |
object |
Key Matching Object. |
{label: string, value: string} |
Required |
Property |
Description |
Type |
newCollection |
Converted collection. |
{label: string, value: string}[] |
import { useStateObject } from '@appello/common';
Hook with state for working with objects:
import { useStateObject } from "@appello/common";
import { setState } from "jest-circus";
const Component = () => {
const [state, setState] = useStateObject({
name: "Test",
lastName: "Jest",
age: 21
});
return (
<>
<span>{JSON.stringify(state)}</span>
<button
type="button"
onClick={() => {
setState(prev => ({
age: prev.age + 25
}));
}}
>
Update using callback
</button>
<button
type="button"
onClick={() => {
setState({
name: "New",
lastName: "Test"
});
}}
>
Update using object
</button>
</>
);
};
Property |
Description |
Type |
Default |
object |
Default object. |
AnyObject |
Required |
Property |
Description |
Type |
state |
Returns a stateful value, and a function to update it. |
[AnyObject, Dispatch<SetStateAction<AnyObject>>] |
import { useSwitchValue } from '@appello/common';
A hook that toggle states.
import { useSwitchValue } from "@appello/common";
const Component = () => {
const { value, on, off, toggle } = useSwitchValue(false);
return (
<>
<p>{`${value}`}</p>
<p>
<button type="button" onClick={on}>
On
</button>
<button type="button" onClick={off} style={{ margin: "0 8px" }}>
Off
</button>
<button type="button" onClick={toggle}>
Toggle
</button>
</p>
</>
);
};
Property |
Description |
Type |
Default |
defaultValue |
Default value. |
boolean |
Required |
Property |
Description |
Type |
value |
Switching value. |
boolean |
on |
Set value true . |
() => void |
off |
Set value false . |
() => void |
toggle |
Toggle value. |
() => void |
import { useUnmountEffect } from '@appello/common';
A hook that executes the function right before the component is unmounted.
import { useUnmountEffect } from "@appello/common";
const Component = () => {
useUnmountEffect(() => {
console.log('Unmount');
});
return <p>Hello World!</p>;
};
Property |
Description |
Type |
Default |
callback |
Callback that is called when the component is unmounted. |
() => void |
Required |
import { useUpdateEffect } from '@appello/common';
A hook alike useEffect
but skips running the effect for the first time.
import { useUpdateEffect } from "@appello/common";
const Component = () => {
const [count, setCount] = useState(0);
const [updateEffectCount, setUpdateEffectCount] = useState(0);
useUpdateEffect(() => {
setUpdateEffectCount((c) => c + 1);
}, [count]);
return (
<div>
<p>updateEffectCount: {updateEffectCount}</p>
<button type="button" onClick={() => setCount((c) => c + 1)}>
reRender
</button>
</div>
);
};
Property |
Description |
Type |
Default |
effect |
Callback that is called when the component is updated. |
() => void |
Required |
deps |
The dependencies list. |
DependencyList |
undefined |
import { useFormPersist } from '@appello/common';
A hook for save temporary data from React hook form inside storage (LocalStorage / SessionStorage / AsyncStorage).
import { useFormPersist } from "@appello/common";
import { Controller } from 'react-hook-form';
import AsyncStorage from '@react-native-async-storage/async-storage';
type FormType = {
name: string;
email: string;
}
const Component = () => {
const [count, setCount] = useState(0);
const [updateEffectCount, setUpdateEffectCount] = useState(0);
const { syncFromStorage, syncToStorage } = useFormPersist<FormType>({
key: 'StorageKey',
storage: AsyncStorage,
});
const {
control,
submit,
watch,
formState: { defaultValues },
} = useForm<ProfileAccountSchemaType>({
schema: ProfileAccountSchema,
defaultValues: () => {
// Sync data form storage (you can select sync-policy)
return syncFromStorage({
defaultValues: {
name: '',
email: ''
},
});
},
})
// Sync to storage
syncToStorage(watch());
return (
<div>
<Controller
control={control}
name="name"
render={({ field: { value, onChange } }) => (
<input
type="text"
value={value}
onChange={onChange}
/>
)}
/>
</div>
);
};
Property |
Description |
Type |
Default |
key |
Key for storage |
string |
Required |
storage |
Object Storage |
Storage |
Required |
excludeFields |
Fields that should not be saved and synchronized |
string[] |
Optional |
includeFields |
fields that should be saved and synchronized |
string[] |
Optional |
Property |
Description |
Type |
syncFromStorage |
Sync values from storage. |
({ defaultValues?: UseFormProps<FieldValues>['defaultValues']; syncPolicy?: CachePolicyLiteral; }) => Promise |
syncToStorage |
Sync values to storage. |
(watchedValues: FieldValues) => void |
clear |
Clear storage by key. |
() => void |