2.0.16 • Published 10 days ago

@appello/common v2.0.16

Weekly downloads
-
License
ISC
Repository
bitbucket
Last release
10 days ago

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

PropertyDescriptionTypeDefault
defaultSecondsCountdown time in seconds. Optional.number59

Return

PropertyDescriptionType
secondsAmount of time in seconds.number
isStartSyntactic sugar. Is the timer running?boolean
sendCodeMethod 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

PropertyDescriptionTypeDefault
firstRefFirst ref.RefRequired
secondRefSecond ref.RefRequired

Return

PropertyDescriptionType
combinedRefCombined 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

PropertyDescriptionTypeDefault
fnCallback for the debounce.AnyFuctionRequired
optionsLodash optionsDebounceOptionsOptional

DebounceOptions:

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

Return

PropertyDescriptionType
debounceInvoke and pass parameters to fn.AnyFuction
cancelCancel the invocation of currently debounced function.() => void
flushImmediately 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

PropertyDescriptionTypeDefault
effectThe effect callback.EffectCallbackRequired
depsThe dependencies list.DependencyListundefined
optionsConfig for the debounce behaviors. See the Options section below for details.DebounceOptionsundefined

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

PropertyDescriptionType
isFirstMountReturn first renderbollean

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

PropertyDescriptionTypeDefault
fnCallback function, a function that will be called with a certain delay.EffectCallbackRequired
delayDelay timenumber1000 ms
immediateStartStarts immediately.bolleanundefined
immediateCallFnIs it necessary to call a callback immediately before the timer starts.bolleanundefined
onStopA callback that will be called after the timer stops.() => voidundefined

Return

PropertyDescriptionType
startFunction for starting timer() => void
stopFunction for stopping timer() => void
setStateFunction 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

PropertyDescriptionTypeDefault
valueFunction, ref or any type value for get last active value.anyRequired

Return

PropertyDescriptionType
resultValueLatest 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

PropertyDescriptionType
updateCallback 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

PropertyDescriptionTypeDefault
callbackCallback for memorize.AnyFunctionRequired

Return

PropertyDescriptionType
callbackFunction 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

PropertyDescriptionTypeDefault
callbackCallback that is called when the component is mounted.AnyFunctionRequired

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

PropertyDescriptionTypeDefault
valueAny value that will be saved.anyRequired

Return

PropertyDescriptionType
valueAny 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

PropertyDescriptionTypeDefault
requestCbAny request function() => Promise<any>Required
defaultParamsAny object.AnyObjectRequired
optionsLodash optionsDebounceOptionsOptional

Return

PropertyDescriptionType
loadingLoading promise.boolean
queryParamsObject with query params.AnyObject
setQueryParamsSet object using dispatch state.React.Dispatch<React.SetStateAction<T>>
updateQueryParamsUpdate query params with.(params: Partial<T>, withDebounce = false) => void
resetReset 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

PropertyDescriptionTypeDefault
collectionCollection of objects to be converted.AnyObject[]Required
objectKey Matching Object.{label: string, value: string}Required

Return

PropertyDescriptionType
newCollectionConverted 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

PropertyDescriptionTypeDefault
objectDefault object.AnyObjectRequired

Return

PropertyDescriptionType
stateReturns 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

PropertyDescriptionTypeDefault
defaultValueDefault value.booleanRequired

Return

PropertyDescriptionType
valueSwitching value.boolean
onSet value true.() => void
offSet value false.() => void
toggleToggle 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

PropertyDescriptionTypeDefault
callbackCallback that is called when the component is unmounted.() => voidRequired

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

PropertyDescriptionTypeDefault
effectCallback that is called when the component is updated.() => voidRequired
depsThe dependencies list.DependencyListundefined

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

PropertyDescriptionTypeDefault
keyKey for storagestringRequired
storageObject StorageStorageRequired
excludeFieldsFields that should not be saved and synchronizedstring[]Optional
includeFieldsfields that should be saved and synchronizedstring[]Optional

Return

PropertyDescriptionType
syncFromStorageSync values from storage.({ defaultValues?: UseFormProps<FieldValues>['defaultValues']; syncPolicy?: CachePolicyLiteral; }) => Promise
syncToStorageSync values to storage.(watchedValues: FieldValues) => void
clearClear storage by key.() => void
2.0.16

10 days ago

2.0.15

5 months ago

2.0.13

5 months ago

2.0.14

5 months ago

2.0.11

6 months ago

2.0.12

5 months ago

2.0.10

6 months ago

2.0.3

6 months ago

2.0.2

6 months ago

2.0.5

6 months ago

2.0.4

6 months ago

2.0.7

6 months ago

2.0.6

6 months ago

2.0.9

6 months ago

2.0.8

6 months ago

2.0.1

6 months ago

2.0.0

6 months ago

1.0.39

6 months ago

1.0.40

6 months ago

1.0.29

10 months ago

1.0.33

9 months ago

1.0.32

9 months ago

1.0.31

10 months ago

1.0.30

10 months ago

1.0.37

7 months ago

1.0.36

8 months ago

1.0.35

8 months ago

1.0.34

9 months ago

1.0.38

7 months ago

1.0.28

12 months ago

1.0.26

1 year ago

1.0.25

1 year ago

1.0.27

1 year ago

1.0.24

1 year ago

1.0.23

1 year ago

1.0.22

1 year ago

1.0.21

1 year ago

1.0.20

1 year ago

1.0.19

1 year ago

1.0.18

1 year ago

1.0.17

1 year ago

1.0.16

1 year ago

1.0.11

2 years ago

1.0.15

1 year ago

1.0.14

2 years ago

1.0.13

2 years ago

1.0.12

2 years ago

1.0.10

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

0.1.20

2 years ago

0.1.21-alpha.0

2 years ago

0.1.19

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.17

2 years ago

0.1.18

2 years ago

0.2.3

2 years ago

0.2.2

2 years ago

0.2.4

2 years ago

0.1.12

2 years ago

0.1.13

2 years ago

0.1.14

2 years ago

0.1.15

2 years ago

0.1.16

2 years ago

0.1.11

2 years ago

0.1.10

3 years ago

0.1.8

3 years ago

0.1.9

3 years ago

0.1.7

3 years ago

0.1.4

3 years ago

0.1.6

3 years ago

0.1.5

3 years ago

0.1.2

3 years ago

0.1.3

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago

0.0.16

3 years ago

0.0.13

3 years ago

0.0.14

3 years ago

0.0.15

3 years ago

0.0.11

3 years ago

0.0.12

3 years ago

0.0.10

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago