※ API 호출 삼대장
npm install axios
axios.create
url 호출 시 필요한 기본 값들 세팅
interceptor
우리가 보낸 요청과 우리가 받은 응답을 확인하기 위해 사용
선택적인 사항
// api.js
import axios from "axios";
// axios.create
const api = axios.create({
// 바뀌지 않은 고정 url
baseURL: "https://api.themoviedb.org/3",
headers: { "Content-type": "application/json" },
});
// interceptor
api.interceptors.request.use(
function (config) {
// Do something before request is sent
// 우리가 보낸 요청을 보고싶다.
console.log("requert start", config);
return config;
},
function (error) {
// Do something with request error
// 에러 확인
console.log("request error", error);
return Promise.reject(error);
}
);
// Add a response interceptor
api.interceptors.response.use(
function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
// 우리가 어떤 데이터를 받았는지 확인하고 싶다.
console.log("get response", response);
return response;
},
function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
// 에러 확인
console.log("response error", error);
return Promise.reject(error);
}
);
export default api;
// movieAction.js
import api from "../api";
const API_KEY = process.env.REACT_APP_API_KEY;
function getMovies() {
return async (dispatch) => {
const popularMovieApi = api.get(
`/movie/popular?api_key=${API_KEY}&language=en-US&page=1`
);
const topRatedApi = api.get(
`/movie/top_rated?api_key=${API_KEY}&language=en-US&page=1`
);
const upComingApi = api.get(
`/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`
);
let [popularMovies, topRatedMovies, upComingMovies] = await Promise.all([
popularMovieApi,
topRatedApi,
upComingApi,
]);
console.log(popularMovies);
console.log(topRatedMovies);
console.log(upComingMovies);
};
}
export const movieAction = { getMovies };