Search code examples
typescriptgoogle-chrome-extensionreact-reduxredux-toolkitweb-ext

REDUX: Dispatch is not update the store


I am working on a project that produces a chrome extension. I am trying to dispatch function in popup.tsx. However not dispatching. My store does not update. The same code works in background page. What can I do that? What could be the problem?

Here is my popup.tsx:

 useEffect(() => {
    if (
      !ip4Cache.hasOwnProperty(hostname) ||
      !geoIPcache.hasOwnProperty(hostname)
    ) {
      console.log('cachede yok')
      checkLookup([hostname]).then((res) => {
        setIp4(res.data['ip4'][hostname])
        dispatch(addIP4(res.data.ip4)) //I also tried store.dispatch in here
       
      })
    }
  }, [hostname])

Here is my store:

let sagaMiddleware = createSagaMiddleware()

const localStorage = createLocalStorage()
const persistConfig = {
  key: 'root',
  storage: localStorage,
}

const reducers = combineReducers({
  ip4: ip4Reducer,
})

export type RootState = ReturnType<typeof reducers>

const createPersistReducer = (config) => persistReducer(config, reducers)

export const store = configureStore({
  reducer: createPersistReducer(persistConfig),
  middleware: [sagaMiddleware],
})
export const persistor = persistStore(store)

sagaMiddleware.run(rootSaga)

wrapStore(store, { portName: 'bla' })

And the last one, IP4 slice:

import { createSlice } from '@reduxjs/toolkit'

export const ip4Slice = createSlice({
  name: 'ip4',
  initialState: {},
  reducers: {
    addIP4: (state, action) =>
      (state = new Object({ ...state, ...action.payload })),
  },
})
export const { addIP4 } = ip4Slice.actions
export default ip4Slice.reducer


Solution

  •   reducers: {
        addIP4: (state, action) => {
          // either:
          Object.assign(state, action.payload);
          // or 
          return { ...state, ...action.payload }
        }
      },
    

    Please give a read to the Writing Reducers with Immer documentation page, especially to Resetting and replacing state.

    Quoting the most important part:

    A common mistake is to try assigning state = someValue directly. This will not work! This only points the local state variable to a different reference. That is neither mutating the existing state object/array in memory, nor returning an entirely new value, so Immer does not make any actual changes.