javascripttypescriptreduxdeno

I can't get a Simple Redux Slice Example from a Tutorial to work


I'm trying to understand how to use Redux Slices but all the tutorials seem to stop before using them, for example this one 30dayscoding.com.

I've implemented their example as far as it goes (and fixed the obvious code error but when I run the code the state does not increment.

Interestingly when I call increment() the log message is not being displayed which implies the reducer is not being called.

Any idea what the issue is?

/* counterSlice.ts */

import { CounterSlice, createSlice } from 'npm:@reduxjs/toolkit@2.2.4'

const counterSlice: CounterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state, action) => {
      console.log('increment')
      state + 1
    },
    decrement: (state, action) => state - 1,
  },
})

export const { increment, decrement } = counterSlice.actions
export default counterSlice.reducer
/* index.ts */

import { configureStore, Store } from 'npm:@reduxjs/toolkit@2.2.4'
import counterSlice from './counterSlice.ts'
import { increment, decrement } from './counterSlice.ts'

const store: Store = configureStore({
  reducer: {
    counter: counterSlice,
  },
})

console.log(store.getState()) // { counter: 0 }
increment()
console.log(store.getState()) // { counter: 0 }

Solution

  • You need to dispatch actions to the store.

    store.dispatch(increment())
    

    Calling increment() alone only creates an "action object" that describes the action, but doesn't execute it - you can take a look at it with console.log(increment()).