@appello/common
TypeScript icon, indicating that this package has built-in type declarations

2.0.16 • Public • Published

Common frontend library of components for web and mobile environmental

How to use it

Download package from npm:

npm i @appello/common

Import modules you need in your code:

import { useInterval, isNill } from '@appello/common';

Development guide

For developers

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.

Hooks

useCodeTimer

import { useCodeTimer } from '@appello/common';

Ready-made hook for setting a timer when sending SMS again

API:

import { useCodeTimer } from "@appello/common";

const { seconds, isStart, sendCode } = useCodeTimer();

const Component = () => {
  return (
    <div>
      ...
      {
        isStart && (
          <span>{seconds}</span>
        )
      }
      <button type="button" onClick={sendCode} />
      ...
    </div>
  );
};

Params

Property Description Type Default
defaultSeconds Countdown time in seconds. Optional. number 59

Return

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

useCombinedRef

import { useCombinedRef } from '@appello/common';

Hook for combining refs.

API:

import { useCombinedRef } from '@appello/common';

const Component = () => {
  const firstRef = useRef<number>(0);
  const secondRef = useRef<number>(0);
  const combinedRef = useCombinedRef(firstRef, secondRef);

  combinedRef(5);
}

Params

Property Description Type Default
firstRef First ref. Ref Required
secondRef Second ref. Ref Required

Return

Property Description Type
combinedRef Combined ref. Ref

useDebounceCallback

import { useDebounceCallback } from '@appello/common';

A hook that deal with the debounced function.

API:

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>
  );
};

Params

Property Description Type Default
fn Callback for the debounce. AnyFuction Required
options Lodash options DebounceOptions Optional

DebounceOptions:

export interface DebounceOptions {
  wait?: number;
  leading?: boolean;
  trailing?: boolean;
  maxWait?: number;
}

Return

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

useDebounceEffect

import { useDebounceEffect } from '@appello/common';

A effect with debounce

API:

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>
    </>
  );
};

Params

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

DebounceOptions:

export interface DebounceOptions {
  wait?: number;
  leading?: boolean;
  trailing?: boolean;
  maxWait?: number;
}

useFirstMountState

import { useFirstMountState } from '@appello/common';

A hook that returns the first rendering

API:

import { useFirstMountState } from '@appello/common';

const Component = () => {
  const isFirstMount = useFirstMountState();
  return console.log(isFirstMount)
};

Return

Property Description Type
isFirstMount Return first render bollean

useInterval

import { useInterval } from '@appello/common';

A hook that allows you to call a callback function in a time interval

API:

import { useInterval } from '@appello/common';

const Component = () => {
  const { start } = useInterval({
    fn: () => {
      console.log('Privet')
    },
  });

  return (
    <button type="button" onClick={start}>
      Start timer
    </button>
  )
};

Params

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

Return

Property Description Type
start Function for starting timer () => void
stop Function for stopping timer () => void
setState Function for switching timer (v: bollean) => void

useLatest

import { useLatest } from '@appello/common';

A Hook that returns the latest value, effectively avoiding the closure problem.

API:

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>
    </>
  );
};

Params

Property Description Type Default
value Function, ref or any type value for get last active value. any Required

Return

Property Description Type
resultValue Latest value. any

useManualUpdate

import { useManualUpdate } from '@appello/common';

A hook that can be used to manually update a component.

API:

import { useManualUpdate } from '@appello/common';

const Component = () => {
  const update = useManualUpdate();

  return (
    <>
      <div>Time: {Date.now()}</div>
      <button type="button" onClick={update}>
        Update
      </button>
    </>
  );
};

Return

Property Description Type
update Callback for update component. () => void

useMemoCallback

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.

API:

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>
    </>
  );
};

Params

Property Description Type Default
callback Callback for memorize. AnyFunction Required

Return

Property Description Type
callback Function that require persistence. AnyFunction

useMountEffect

import { useMountEffect } from '@appello/common';

A hook that executes a function after the component is mounted.

API:

import { useMountEffect } from '@appello/common';

const Component = () => {
  useMountEffect(() => {
    console.log("Mount")
  })

  return (
    <span>component</span>
  );
};

Params

Property Description Type Default
callback Callback that is called when the component is mounted. AnyFunction Required

usePrevious

import { usePrevious } from '@appello/common';

A Hook to return the previous state.

API:

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>
    </>
  );
};

Params

Property Description Type Default
value Any value that will be saved. any Required

Return

Property Description Type
value Any value that saved. any

useQueryParamsBuilder

import { useQueryParamsBuilder } from '@appello/common';

A Hook for manager query params with debounce time

API:

import { useQueryParamsBuilder } from '@appello/common';

const Component = () => {
  const [getService, { data }] = useAnyRequest();

  const { updateQueryParams } = useQueryParamsBuilder({
    queryCb: params => getService(params),
    defaultParams: {
      categoryId,
      search: '',
    },
  });
  
  return (
    <></>
  );
};

Params

Property Description Type Default
requestCb Any request function () => Promise<any> Required
defaultParams Any object. AnyObject Required
options Lodash options DebounceOptions Optional

Return

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

useSelectOptions

import { useSelectOptions } from '@appello/common';

Converts dictionaries for picker to structure:

[
  {
    value: 1,
    label: 'Select 1'
  }, {
    value: 2,
    label: 'Select 2'
  }
]

API:

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>
  );
};

Params

Property Description Type Default
collection Collection of objects to be converted. AnyObject[] Required
object Key Matching Object. {label: string, value: string} Required

Return

Property Description Type
newCollection Converted collection. {label: string, value: string}[]

useStateObject

import { useStateObject } from '@appello/common';

Hook with state for working with objects:

API:

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>
    </>
  );
};

Params

Property Description Type Default
object Default object. AnyObject Required

Return

Property Description Type
state Returns a stateful value, and a function to update it. [AnyObject, Dispatch<SetStateAction<AnyObject>>]

useSwitchValue

import { useSwitchValue } from '@appello/common';

A hook that toggle states.

API:

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>
    </>
  );
};

Params

Property Description Type Default
defaultValue Default value. boolean Required

Return

Property Description Type
value Switching value. boolean
on Set value true. () => void
off Set value false. () => void
toggle Toggle value. () => void

useUnmountEffect

import { useUnmountEffect } from '@appello/common';

A hook that executes the function right before the component is unmounted.

API:

import { useUnmountEffect } from "@appello/common";

const Component = () => {
  useUnmountEffect(() => {
    console.log('Unmount');
  });

  return <p>Hello World!</p>;
};

Params

Property Description Type Default
callback Callback that is called when the component is unmounted. () => void Required

useUpdateEffect

import { useUpdateEffect } from '@appello/common';

A hook alike useEffect but skips running the effect for the first time.

API:

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>
  );
};

Params

Property Description Type Default
effect Callback that is called when the component is updated. () => void Required
deps The dependencies list. DependencyList undefined

useFormPersist

import { useFormPersist } from '@appello/common';

A hook for save temporary data from React hook form inside storage (LocalStorage / SessionStorage / AsyncStorage).

API:

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>
  );
};

Params

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

Return

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

Readme

Keywords

Package Sidebar

Install

npm i @appello/common

Weekly Downloads

258

Version

2.0.16

License

ISC

Unpacked Size

431 kB

Total Files

102

Last publish

Collaborators

  • victor-razdorov
  • yaro-appello
  • kuzkokov