728x90
공식문서 : https://reactnative.dev/docs/network
Networking · React Native
Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may need to fetch a chunk of static content from another server.
reactnative.dev
1. 설명 :
ㄱ. fetch는 react-native에서 제공하는 기본 네트워킹 API다.
ㄴ. JSON으로 구성된 URL에서 데이터를 가져올 수 있다.
ㄷ. 네트워킹은 본질적으로 비동기(Async)다. ( 비동기 참고자료 : https://koras02.tistory.com/87 )
(요컨데, 비동기는 멀티태스킹이 된다는 소리다.)
ㄹ.
2. 기본 사용법
ㄱ. useState 선언
const [state, setState] = useState([]) // 사용할 데이터를 치환해줄 변수
const [loading, setLoading] = useState(true); // 로딩화면 만들어줄 변수
const [error, setError] = useState(null); // 에러 잡아줄 변수
ㄴ. fetch .then .catch 삽입
함수 선언 후, return값으로 반환한다.
fetch로 url을 받고, .then으로 json으로 반응하라 하고, .catch로 에러를 잡는다.
const getMoviesFromApi = () => {
return fetch('https://reactnative.dev/movies.json')
.then((response) => response.json())
.then((json) => {
return json.movies;
})
.catch((error) => {
console.error(error);
});
};
ㄷ. 로딩중이거나 에러가 날 경우, return값 지정.
if (isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="#5500dc" />
</View>
);
}
if (error) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 18 }}>
Error fetching data... Check your network connection!
</Text>
</View>
);
}
ㄹ. Async 구문 사용 할 때 바꿔줄화면
const getMoviesFromApiAsync = async () => {
try {
const response = await fetch(
'https://reactnative.dev/movies.json'
);
const json = await response.json();
return json.movies;
} catch (error) {
console.error(error);
}
};
728x90
'React-native > 정리' 카테고리의 다른 글
Flatlist + SearchBar (2편 <FlatList> Header형) (0) | 2022.05.25 |
---|---|
Flatlist + SearchBar (1편 <TextInput> 태그형) (0) | 2022.05.25 |
FlatList + Iframe 연동 (0) | 2022.05.23 |
Infinite Flatlist + Firebase 연동하기 (0) | 2022.05.22 |
기본 학습 (0) | 2022.05.21 |