UNPKG

react-auto-controlled

Version:

Component autonomous state control utilities in React class methods and React Hooks

59 lines (58 loc) 2.65 kB
import { GetDerivedStateFromProps } from 'react'; import { AnyObject } from './AnyObject'; import { AutoControlled } from './AutoControlled'; /** * A manager providing methods which can automatically update very * specific key-value pairs of a component's state object as provided. * * Mimics the `<AutoControlledComponent>` class from the * `semantic-ui-react` / `@stardust-ui/react` packages * in terms of behavior although it is not meant to be inherited. * * @export * @class AutoControlledManager * @implements {AutoControlledManager<State, Props>} * @template State * @template Props */ export declare class AutoControlledManager<State extends AnyObject, Props extends Partial<State>> implements AutoControlled<State> { /** * A list of props auto controlled by its manager's functions. * * @type {(keyof State)[]} */ readonly autoControlledProps: (keyof State)[]; /** * Builds state from new props & old state whenever the component updates, * including during the component's initial render itself. * * @param {object} nextProps New props. * @param {object} prevState Old state. * @returns {(object | null)} New state object if the state depends on props or * `null` if there is nothing for the state to derive from. */ readonly getDerivedStateFromProps: GetDerivedStateFromProps<Props, State>; /** * Builds initial state from props that might be controlled by the user. * * @param {object} props Props possibly controlled by the user. * @returns {object} Full initial state of the component. */ readonly getInitialAutoControlledStateFromProps: (props: Props) => State; /** * Creates an instance of `AutoControlledManager`. * @param {(keyof State)[]} autoControlledProps Keys to props which will be converted into the component's auto-controlled internal state. * @param {{ * getInitialAutoControlledState?: (props: Props) => State; * getAutoControlledStateFromProps?: ( * props: Props, * state: State * ) => Partial<State>; * }} [propsToStateDerivers={}] A set of methods which determine the component's initial state and the state after every rerender. */ constructor(autoControlledProps: (keyof State)[], propsToStateDerivers?: { getInitialAutoControlledState?: (props: Props) => State; getAutoControlledStateFromProps?: (props: Props, state: State) => Partial<State>; }); trySetState(maybeState: Partial<State>, callback?: () => void): void; }