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 } }
'Face the fear, build the future > Revision Sector' 카테고리의 다른 글
Note - To harmonise Redux & async data with axios (0) | 2022.12.31 |
---|---|
실용적일것 같은 JS Design Pattern (0) | 2022.12.30 |
Redux Toolkit 에 대해 알아보기. (0) | 2022.12.26 |
How to know 'Design Pattern' as the developer? (1) | 2022.12.16 |
react 에서 context 와, Provider 는 무슨 용도일까. (0) | 2022.12.15 |