1. 리덕스와 FireStore
- firestore를 리덕스 스토어 넣기 위해서 미들웨어가 필요하다.
- 액션 -> 미들웨어 -> 리듀서 순으로 처리가 된다.
1.1 redux-thunk
- 객체 대신 함수를 생성하는 액션 생성 함수를 작성 가능
- 패키지 설치
yarn add redux-thunk
미들웨어 추가(configStore.js)
import { createStore, combineReducers, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import bucket from "./modules/bucket";
import { createBrowserHistory } from "history";
export const history = createBrowserHistory();
const middlewares = [thunk];
const enhancer = applyMiddleware(...middlewares);
const rootReducer = combineReducers({ bucket });
const store = createStore(rootReducer, enhancer);
export default store;
1.2 리덕스에 Firestore 적용
Firebase와 통신하는 함수 만들기
const bucket_db = firestore.collection("bucket");
// 파이어베이스와 통신
export const loadBucketFB = () => {
return function (dispatch) {
bucket_db.get().then((docs) => {
let bucket_data = [];
docs.forEach((doc) => {
// 도큐먼트 객체를 확인
console.log(doc);
// 도큐먼트 데이터 가져오기
console.log(doc.data());
// 도큐먼트 id 가져오기
console.log(doc.id);
if(doc.exists){
bucket_data = [...bucket_data, ];
}
});
console.log(bucket_data);
// 액션 생성 함수에 가져온 데이터 넣기
dispatch(loadBucket(bucket_data));
});
};
};
리듀서 고치기
...
case "bucket/LOAD": {
if(action.bucket.length >0){
return { list: action.bucket };
}
return state;
}
...
사용하기
...
// loadBucketFB를 import
// load()를 componentDidMount에서 호출
const mapDispatchToProps = (dispatch) => ({
load: () => {
dispatch(loadBucketFB());
},
create: (new_item) => {
dispatch(createBucket(new_item));
}
});
...
Reference
'programming study > 항해99 커리큘럼' 카테고리의 다른 글
[항해99 1기] [Chapter3-2] 주특기 심화 - 리액트 심화반 (2) (2021.3.27) (0) | 2021.03.27 |
---|---|
[항해99 1기] [Chapter3-2] 주특기 심화 - 리액트 심화반 (1) (2021.3.26) (0) | 2021.03.26 |
[항해99 1기] [Chapter3-1] 주특기 기본 - 프론트의 꽃 리액트 (9) (2021.3.23) (0) | 2021.03.23 |
[항해99 1기] [Chapter3-1] 주특기 기본 - 프론트의 꽃 리액트 (6) (2021.3.22) (0) | 2021.03.23 |
[항해99 1기] [Chapter3-1] 주특기 기본 - 프론트의 꽃 리액트 (8) (2021.3.23) (0) | 2021.03.23 |