관리 메뉴

Silver Library (Archived)

[Redux Toolkit] How should I configure 'Store' 본문

Face the fear, build the future/Revision Sector

[Redux Toolkit] How should I configure 'Store'

Ayin Kim 2022. 12. 31. 21:37
반응형

There is something called 'A design pattern for Redux'. In this post, let's research how 'store' concept can be used.

 

Do remember, Redux life cycle should be:

Action Creator -> Action -> Dispatch -> Reducers -> Store

Which means:

You -> Booking Form -> Submit Form -> Ticket Counters -> Movie Cinema

 

Point is; Config slice then set store.

 

cakeSlice.js

create feature slice using createSlice function. This generates the actions and reducers.

const createSlice = require('@reduxjs/toolkit').createSlice

const initialState = {
	numOfCakes: 10,
}

const cakeSlice = createSlice({
	name: 'cake',
    initialState,
    reducers: {
    	ordered: (state) => {
        	state.numOfCaes--
        },
        restocked: (state, action) => {
        	state.numOfCakes += action.payload
        },
    },
})

module.exports = cakeSlice.reducer
module.exports.cakeActions = cakeSlice.actions

store.js

Created store using 'configureStore'. This allowed attaching 'reducer'.

const configureStore = require('@reduxjs/toolkit').configureStore
const cakeReducer = require('../features/cake/cakeSlice')

const store = configureStore({
	reducer: {
    	cake: cakeReducer,
    },
})

module.exports = store

index.js

dispatch actions on the 'store' using store.dispatch. 

Inspect the state using store.getState

and listen to changes using store.subscribe

const store = requrie('./app/store')
const cakeActions = require('./features/cake/cakeSlice').cakeActions

console.log('Initial state ', store.getState())
const unsubscribe = store.subscribe(() => {
	console.log('Updated state ', store.getState())
})

store.dispatch(cakeActions.ordered())
store.dispatch(cakeActions.ordered())
store.dispatch(cakeActions.ordered())
store.dispatch(cakeActions.restocked(3))

unsubscribe()

// On terminal:
// Initial state { cake: { numOfCakes: 10 } }
// Updated state { cake: { numOfCakes: 9 } }
// Updated state { cake: { numOfCakes: 8 } }
// Updated state { cake: { numOfCakes: 7 } }
// Updated state { cake: { numOfCakes: 10 } }