0

I am using redux/toolkit and entity adapter in my app. The problem is that when I want to add selectors to my slice I got undefined for store.getState();

I write this based on Redux Toolkit documentation.

driverReducer.ts

const driversAdapter = createEntityAdapter<Driver>({
  sortComparer: (a, b) => a.name.localeCompare(b.name),
});

export const DriverSlice = createSlice({
  name: "drivers",
  initialState: driversAdapter.getInitialState(),
  reducers: {
    setDrivers: driversAdapter.setAll,
    driverAdded: driversAdapter.addOne,
    driverUpdated: driversAdapter.updateOne,
    driverRemoved: driversAdapter.removeOne,
  },
});

const driversSelectors = driversAdapter.getSelectors<RootState>(state => state.drivers);
export const selectAllDrivers = driversSelectors.selectAll(store.getState());


export default DriverSlice.reducer;

store.ts

export const store = configureStore({
  reducer: {
    drivers:driverReduces,
  },
});

How can I fix this issue?

2
  • Where exactly are you getting that error message? Commented Oct 1, 2021 at 9:42
  • I got this error when adding store.getState() to the driversSelectors.selectAll . @phry Commented Oct 1, 2021 at 11:14

1 Answer 1

3

You have a circular dependency here.

Your store.ts needs to import DriverSlice from driverReducer.ts. Your driverReducer.tsneeds to import store from store.ts.

A file can only be evaluated fully, so with both files having to be evaluated before the other, that's just not possible.

Solution? Move your export const selectAllDrivers = driversSelectors.selectAll(store.getState()); to another file.

Also note, that selectAllDrivers will be the result of evaluating driversSelectors.selectAll(store.getState()) once at the beginning - so it will likely just be your initial state. That is probably not what you want, but not really the subject of this question.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, @phry. Moving those selectors to another file disappeared the error. However, I cannot get the drivers from my component by calling selectAllDrivers . It returned an empty array as a list of drivers.
Because you do not use selectors like that, at all. Where are you planning to use those? In a React component?
Yes, in a react component. I can use driversSelectors.selectAll(store.getState()) in my component and it works. But, this is not the best way for getting state. What do you suggest?
Never call store.getState() in your component. You need to use react-redux for that. Otherwise store changes will not udpate the component with relevant data. const myData = useSelector(driversSelector.selectAll)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.