rsm-hcd / AndcultureCode.JavaScript.React

Common patterns, functions, etc... used when building react applications
6 stars 8 forks source link

Type alias for Dispatch<SetStateAction<T>> #52

Open brandongregoryscott opened 3 years ago

brandongregoryscott commented 3 years ago

A simple type alias around React's dispatch/set state action types would reduce verbosity while still getting the point across.

Something like this:

import { Dispatch, SetStateAction } from "react";

export alias type SetState<T> = Dispatch<SetStateAction<T>>;

Before:

const validate = (value: string, setError: Dispatch<SetStateAction<string>>) => {
    if (StringUtils.isEmpty(value)) {
        setError("Value cannot be empty!");
        return false;
    }

    return true;
}

const updateUser = (user: UserRecord, setContext: Dispatch<SetStateAction<UserContextRecord>>) => {
    // ... business logic ...
    setContext((prevState: UserContext) => prevState.with({ user }));
    return;
}

After:

const validate = (value: string, setError: SetState<string>) => {
    if (StringUtils.isEmpty(value)) {
        setError("Value cannot be empty!");
        return false;
    }

    return true;
}

const updateUser = (user: UserRecord, setContext: SetState<UserContextRecord>) => {
    // ... business logic ...
    setContext((prevState: UserContext) => prevState.with({ user }));
    return;
}

Open to other suggestions for naming convention, too - that was just my first thought