question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

"Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization" error in RTK Query

See original GitHub issue

What exactly am I doing wrong here?

As soon as I add builder.addMatcher to extraReducers, I start getting an error. Everything works fine before I add it. totally the problem is related to my adding extraReducers. But I didn’t understand what I did wrong.

extraReducers: (builder) => {
    builder.addMatcher(
      authenticationApi.endpoints.postLogin.matchFulfilled,
      (state, { payload }) => {
        state.isLogin = true;
        state.token = payload.data;
      }
    )
  },

Store image Slice image Api image Api call page image Error image

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:8

github_iconTop GitHub Comments

2reactions
markeriksoncommented, May 12, 2022

I think the issue is you have a circular import problem. The API file is importing the baseQuery, baseQuery imports the auth action, and the auth slice imports the API.

You’re probably going to need to rearrange that logic to fix the circle.

I don’t have an immediate answer on how to best do that atm - ironically I’m in the middle of fixing a bunch of circular imports in my own app and that’s taking up all my brain space 😃

0reactions
MartinMasekcommented, Jun 21, 2022

The problem

I’ve resolved the issue so I think it deserves a little context first because I struggled to google answer fast.

My app uses Network.ts (basically a static class - singleton) file. The app uses Network.fetch instead of system fetch. The reason is so I can pass access token with every request.

Now this Network class is basically a wrapper around fetch and if it sees 401 it wants to dispatch empty auth state so user is shown “Not authenticated” screen

The issue is that when you init a new project using https://github.com/reduxjs/cra-template-redux-typescript (which you are so kind to contribute @markerikson) it doesn’t have a scenario for when you want to update the store from outside React component.

When there is UI action (say user clicks a button) it triggers Redux async action which uses internally the Network.ts class. That causes the problem as I described above.

The solution:

Keep the authSlice.ts file but create new auth-actions.ts, auth-reducers.ts and auth-types.ts The files can look like this (rather focus on the concept) auth-types.ts

export const AUTH_LOCAL_STORAGE_KEY = 'auth-token'
export const AUTH_SLICE_NAME = 'auth'
export const SET_AUTH_STATE_ACTION_NAME = 'setAuthState'

export type AuthReduxState = {
    isAuthenticated: boolean
    ... // other props
}

export const getEmptyAuthState = (): AuthReduxState => {
    return { ... }
}

auth-actions.ts

import authSlice from './authSlice'

export const { setAuthState, ... } = authSlice.actions

auth-reducers.ts

import authSlice from './authSlice'

export default authSlice.reducer`

The authSlice.ts file looks like a typical Slice with one change

export const authSlice = createSlice({
    name: AUTH_SLICE_NAME,
    initialState: getEmptyAuthState(),
    reducers: {
        [SET_AUTH_STATE_ACTION_NAME]: (_, action: PayloadAction<AuthReduxState>) => {
            return action.payload
        },
        ...
    },
})

export default authSlice

The store.ts has a slight change

import authReducers from './auth/auth-reducers'

reducer: {
        auth: authReducers,
    },

And finally the Network.ts can dispatch to store

...
if (result.status === 401) {
            localStorage.removeItem(AUTH_LOCAL_STORAGE_KEY)
            store.dispatch({ type: `${AUTH_SLICE_NAME}/${SET_AUTH_STATE_ACTION_NAME}`, payload: getEmptyAuthState() })
        }
Read more comments on GitHub >

github_iconTop Results From Across the Web

Redux Cannot access '__WEBPACK_DEFAULT_EXPORT__ ...
A few minutes into the refactoring, I was encountered with Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization .
Read more >
redux cannot access before initialization - You.com
I have made a React site using redux which is successfully working on one component. This is mapped to props and pulls data...
Read more >
Redux-Toolkit & Solving “ReferenceError: Access lexical ...
Last week, I had a really annoying error in one of our ... ReferenceError: can't access lexical declaration 'loadPage' before initialization ...
Read more >
Code Splitting - Redux Toolkit
Code Splitting. RTK Query makes it possible to trim down your initial bundle size by allowing you to inject additional endpoints after ...
Read more >
Redux Essentials, Part 8: RTK Query Advanced Patterns
Cache Data Subscription Lifetimes​. Let's try this out and see what happens. Open up your browser's DevTools, go to the Network tab, and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found