$ yarn add @reduxjs/toolkit
const addTodo = createAction('ADD');
🔻 기존 코드
const ADD = "ADD";
const addTodo = text => {
return {
type: ADD,
text
}
}
const reducer = createReducer([], { // 첫번째 인자 = initialState
[addtodo]: (state, action) => {
state.push( // 셍략 );
}
...
});
🔻 기존 코드 (switch문)
const reducer = (state = [], action) => {
switch (action.type) {
case ADD:
const addItem = [...state, { text: action.text, id: Date.now() }];
localStorage.setItem('wishes', JSON.stringify(addItem));
return addItem;
...
}
redux의 createStore의 업그레이드 버전.
(이제 IDE에서도 createStore말고 configureStore를 권장함)
-> redux-devtool도 지원함.
const store = configureStore({ reducer });
🔻 기존 코드
const store = createStore(reducer);
📝 공식 문서 참조
- If it is an object of slice reducers, like {users : usersReducer, posts : postsReducer}, configureStore will automatically create the root reducer by passing this object to the Redux combineReducers utility.
-> 만약 객체 안에 리듀서가 한개면 그것이 자동으로 루트리듀서가 되고,
리듀서가 여러개라면 configureStore이 자동으로 루트 리듀서를 만들어서 사용함.
-> 자동으로 redux-devtool이 연동된다!
❗️ 이전에는 createStore()의 두번째 인자로
composeWithDevTools
를 넣어줘야 했음.import { composeWithDevTools } from 'redux-devtools-extension'; const store = createStore(rootReducer, composeWithDevTools());
store.js
import { configureStore, createAction, createReducer } from '@reduxjs/toolkit';
const addWish = createAction('ADD', (text) => ({ payload: { text } }));
const deleteWish = createAction('DELETE', (id) => ({ payload: { id } }));
const clearAll = createAction('CLEAR');
/*
const addWish = (text) => {
return {
type: ADD,
text,
};
};
const deleteWish = (id) => {
return {
type: DELETE,
id,
};
};
const clearAll = () => {
return {
type: CLEAR,
};
};
*/
console.log(addWish());
JSON.parse(localStorage.getItem('wishes')) ||
localStorage.setItem('wishes', JSON.stringify([]));
const reducer = createReducer(JSON.parse(localStorage.getItem('wishes')), {
[addWish]: (state, action) => {
const addItem = [...state, { text: action.payload.text, id: Date.now() }];
localStorage.setItem('wishes', JSON.stringify(addItem));
state.push({ text: action.payload.text, id: Date.now() });
},
[deleteWish]: (state, action) => {
const deleteItem = state.filter((toDo) => toDo.id !== action.payload.id);
localStorage.setItem('wishes', JSON.stringify(deleteItem));
return deleteItem;
},
[clearAll]: (state, action) => {
localStorage.setItem('wishes', JSON.stringify([]));
return [];
},
});
const store = configureStore({ reducer });
export const actionCreators = {
addWish,
deleteWish,
clearAll,
};
export default store;