1

In Zustand, I need to initialize a few values using functions. Some of these initializers need other (initialized) values from the store. This is a simplified example:


type BearState =
    {
        whiteBears: number;
        brownBears: number;
    };

const useBearStore = create<BearState>()((set, get) => 
{
    function initWhiteBears(): number
    {
        return 10;
    }

    function initBrownBears(): number
    {
        const state = get();

        return state.whiteBears * 2;
    }

    return {
        whiteBears: initWhiteBears(),
        brownBears: initBrownBears()
    };
});

The error I'm getting is at the line const state = get();. state is undefined.

How can I initialize state using other pieces of state at the very beginning of the program?

sw1337
  • 533
  • 4
  • 16

0 Answers0