공식 HP : https://reactnative.dev/docs/network
react native에서도 JS의 Fetch API를 통해 통신 가능
비동기 방식으로 response를 다루는 방법도 동일
import React, {useEffect, useState} from 'react';
import {ActivityIndicator, FlatList, Text, View} from 'react-native';
type Movie = {
id: string;
title: string;
releaseYear: string;
};
const App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState<Movie[]>([]);
const getMovies = async () => {
try {
const response = await fetch('https://reactnative.dev/movies.json');
const json = await response.json();
setData(json.movies);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
useEffect(() => {
getMovies();
}, []);
return (
<View style={{flex: 1, padding: 24}}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={data}
keyExtractor={({id}) => id}
renderItem={({item}) => (
<Text>
{item.title}, {item.releaseYear}
</Text>
)}
/>
)}
</View>
);
};
export default App;
ActivityIndicator은 로딩 중임을 표시하는 원형 모양을 나타낸다.
(공식 HP : https://reactnative.dev/docs/activityindicator )
WebSocket으로 양방향 통신도 가능
참고 : https://www.youtube.com/watch?v=7mzw4a_Wob4&list=PLaHIVvYn0_AvI_qfaPTi1Wm4gioyWP-KZ&index=9