immerjs / use-immer

Use immer to drive state with a React hooks
MIT License
4.04k stars 92 forks source link

[Question] Using union type in useImmerReducer #126

Closed Sebastian-Nielsen closed 9 months ago

Sebastian-Nielsen commented 9 months ago

What I am trying to do: Fetch some data and then feed it to editProfileReducer with dispatch.

Draft is a union type of the three different states the reducer can be in. What am I doing wrong here?

It seems useReduceImmer is not treating the values of loadingStatus as its respective constant (e.g. loadingStatus: 'loading') but instead treats it as string.

function Foo() {
                     // Type-error here:              v---------------v
    const [userData, dispatch] = useImmerReducer(editProfileReducer, {
        loadingStatus: 'loading',
        userData: undefined,
        error: undefined,
    });
    return <div></div>
}

export type Draft = {
    loadingStatus: 'success',
    userData: UserData,
    error: undefined,
} | {
    loadingStatus: 'loading',
    userData: undefined,
    error: undefined,
} | {
    loadingStatus: 'error',
    userData: undefined,
    error: any;
}

export function editProfileReducer(
    draft: Draft, action: Action
) {
    return {
        loadingStatus: 'loading',
        userData: undefined,
        error: undefined,
    };
}

The above results in:

image