keajs / kea

Batteries Included State Management for React
https://keajs.org/
MIT License
1.94k stars 51 forks source link

Accessing whole state in reducers #145

Closed rschyboll closed 2 years ago

rschyboll commented 2 years ago

Hi, it's me again, this time with a simpler question.

Is it possible to somehow access the whole state in a reducer? I would like to update only part of state based on some other state in the logic. For example:

interface BookData {
  name: string;
  otherData: any;
}

const bookLogic = kea<bookLogicType>({
  actions: {
    changeBookName: (name: string) => ({ name }),
  },
  reducers: {
    currentBook: [null as number | null, {}],
    books: [
      {} as {
        [key: number]: BookData;
      },
      {
        changeBookName: (books, { name }) => {
          //Access current book and update it's name
        },
      },
    ],
  },
});

In this example i would like to update the book, that is currently selected by the reducer "currentBook", but in the "books" reducer i have no access to it.

I tried to access values in reducers, but when accessing any value, i'm getting such an error: Uncaught (in promise) Error: You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store. at Object.getState (redux.js:188:13) at Object.i [as getState] (<anonymous>:2486:24) at getStoreState (index.esm.js:1380:29) at Object.get [as currentLayoutId] (index.esm.js:994:39) at Object.createWindow [as create window (kea.logic.4)] (eval at hmrApply (runtime-1020c34fb604e8d9.js:322:16), <anonymous>:82:50) at index.esm.js:522:34 at combination (index.esm.js:853:26) at combination (index.esm.js:853:26) at combination (index.esm.js:853:26) at Object.combination [as combined] (index.esm.js:853:26)

Do i have to do some magic in a listener or action to update the current book? Or is there some other way to structure such a logic?

Thanks in advance :)

rschyboll commented 2 years ago

Now i realized that this might be a stupid question. Reducers should be separate states that are not dependent on each other, am i right? I thought otherwise, because of transitioning from redux-toolkit, where a single slice of data was a single reducer, and i structured the logic based on that slice, but a single logic contains many reducers. I guess i answered myself, closing the issue :)