fetch 확인
movies data -> jason.data.movies
.then((json) => console.log(json.data.movies));
원하는 정보 확인
useEffect(() => {
.then((response) => response.json())
.then((json) => {
setMovies(json.data.movies);
setLoading(false);
});
}, [])
요즘 더 자주 쓰는 방법!
async() & await
const getMovies = async() => {
const response = await fetch("https://yts.mx/api/v2/list_movies.json?minimum_rating=8.5&sort_by=year");
const json = await response.json();
setMovies(json.data.movies);
setLoading(false);
};
useEffect(() => {
getMovies();
}, []);
Shorcut
const getMovies = async() => {
const json = await(await(fetch(`https://yts.mx/api/v2/list_movies.json?minimum_rating=8.5&sort_by=year`))).json();
setMovies(json.data.movies);
setLoading(false);
};
cf) array로 반환
return(
<div>
{loading ? <h1>Loading....</h1>:
<div>{movies.map(movie => <div key={movie.id}> {movie.title}</div>)}</div>}
</div>);
axios 사용하여 api 가져오기
axios를 가장 많이들 사용하니 많이 써보도록 하자.
1)
const getMovies = () =>{
.then((Response) => {console.log(Response.data)})
.catch((Error) => {console.log(Error)})
}
2) setMovies & setLoading
const getMovies = async() =>{
try{
.then((res) => {
setMovies(res.data.movies);
setLoading(false);
console.log("성공");
})
}catch(e){
console.log(e);
}
}
하지만... 이렇게 하면 movies 제대로 안 가져와짐..
ㅠㅠ 슬프군
더 공부하고 도전해봐야겠따.
[REACT] Axios
AJAX: JS의 라이브러리 중 하나, 브라우저가 가지고 있는 XMLHttpRequest 객체를 이용하여 전체 페이지를 새로 고치지 않고도 페이지의 일부만을 한 데이터 로드 -> 즉, JS를 통해서 서버에 데이터 요청
portfolio0421.tistory.com
*Cannot read properties of undefined (reading 'map') 오류 해결 방법
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [loading, setLoading] = useState(true);
const [movies, setMovies] = useState([]);
const getMovies = async() =>{
try{
.then((res) => {
setMovies(res.data.movies);
setLoading(false);
console.log("성공");
})
}catch(e){
console.log(e);
}
}
useEffect(() => {
getMovies();
}, []);
console.log(movies);
return(
<div>{ movies.map((movie) => <div key={movie.id}>{movie.title}</div>)}</div>
);
}
export default App;
오류의 이유?
React 는 렌더링이 화면에 커밋 된 후에 모든 효과를 실행하기 때문이다.
즉 React는 return에서 map 함수를 반복실행할 때 첫 턴에 데이터가 안들어와도 렌더링이 되며 당연히
그 데이터는 undefined로 정의되어 오류가 나는 것이다.
구글링해보니 해결 방법이 useState()에 빈 배열 초기값으로 선언 or && 사용 요 두가지였는데
전자의 상황에서 에러가 뜬 상황이기 때문에 후자로 해결했다!
<div>{movies && movies.map((movie) => <div key={movie.id}>{movie.title}</div>)}</div>
'FE > React & TS' 카테고리의 다른 글
Sass / styled-components (0) | 2023.05.16 |
---|---|
[REACT Movie App part-two] React-router / react-router-dom (0) | 2023.05.11 |
[REACT] Axios (0) | 2023.05.11 |
[REACT] "Coin Tracker" fetch / useEffect / map / api data (0) | 2023.05.10 |
[REACT] Event (0) | 2023.05.09 |