백엔드에서 api와 db를 만들어주기 전에 가상의 데이터를 만들어서 뷰에 뿌려보기 위한 목적.
// /shared/response.js
const RESP = {
ARTICLE: {
articles: [
{
id: "1",
username: "임꺽정",
content: "내용",
saying: "명언이다",
createdAt: "12:33",
},
{
id: "2",
username: "홍길동",
content: "팀장님이 이상해요",
saying: "이 또한 지나가리",
createdAt: "12:33",
},
],
},
};
export default RESP;
// /redux/modules/articles.js
import RESP from "../../shared/response";
...
const resp = RESP.ARTICLE;
for (let i=0; i<resp.length; i++) {
....
}
HTTP 비동기 통신 라이브러리로 axios를 사용해보았다.
yarn add axios
// shared/Request.js
import axios from "axios";
...
const instance = axios.create({
baseURL: "요청보낼 서버 도메인" // 요청을 www.aa.com/user로 보낸다면, www.aa.com까지 기록
});
// 가지고 있는 토큰 넣어주기!
// 로그인 전이면 토큰이 없으니 못 넣어요.
// 그럴 땐 로그인 하고 토큰을 받아왔을 때 넣어줍시다.
instance.defaults.headers.common["Authorization"] = USER_TOKEN;
export default instance;
// /redux/modules/someModule.js
import instance from "../../shared/Request";
...
// 어떤 미들웨어
const getSomeData = () => {
return function(dispatch){
// 만들어둔 instance에 보낼 요청 타입과 주소로 요청합니다.
instance.get("/some").then((res) => {
//요청이 정상적으로 끝나고 응답을 받아왔다면 수행할 작업!
}).catch(err => {
// 요청이 정상적으로 끝나지 않았을 때(오류 났을 때) 수행할 작업!
console.log("에러 났어!");
})
}
}