React Native에서 서버로부터 데이터를 불러오려면 fetch API를 사용하면 됩니다. fetch API는 XMLHttpRequest나 다른 네트워킹 API와 유사하게 동작하며, 훨씬 간결한 문법으로 HTTP 요청을 처리할 수 있습니다.
fetch API 기본 사용법
fetch를 사용하면 서버에 요청을 보내는 작업이 매우 간단합니다. 다음 코드를 살펴보세요.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => response.json())
.then((responseJson) => console.log(responseJson));위 코드는 https://jsonplaceholder.typicode.com/posts/1 경로의 JSON 데이터를 가져와서 콘솔에 출력하는 예제입니다. fetch() API의 가장 기본적인 호출 방식은 인자를 하나만 받는데, 바로 데이터를 가져올 경로(URL)입니다. 그리고 fetch는 응답(response)을 담은 Promise를 반환합니다.
fetch API가 반환하는 Promise에는 HTTP 응답 객체가 들어 있으며, 여기서 JSON 본문을 추출하려면 json() 메서드를 사용해야 합니다.
또한 fetch의 두 번째 인자로 객체를 전달할 수 있는데, 이 객체에는 HTTP 메서드(GET, POST 등), 헤더(headers), 전송할 데이터 등을 설정할 수 있습니다.
예제: fetch API로 GET 요청 보내기
이제 서버에서 데이터를 가져와 사용자에게 화면에 표시하는 실제 동작 예제를 살펴보겠습니다.
1. state 초기화
먼저 데이터를 저장할 state 변수를 빈 값으로 초기화합니다.
state = {
data: ''
}2. componentDidMount() 이해하기
fetch API 호출은 componentDidMount() 함수 안에서 수행합니다. componentDidMount()는 컴포넌트가 마운트된 직후, 즉 화면에 모든 요소가 렌더링된 직후에 자동으로 호출되는 라이프사이클 메서드입니다. 따라서 화면이 표시되는 즉시 서버에서 데이터를 받아올 수 있습니다.
코드는 다음과 같습니다.
componentDidMount = () => {
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
}위 URL에서 반환되는 데이터는 다음과 같습니다.
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}이 예제에서는 body 필드의 텍스트를 화면에 표시하는 것이 목표입니다.
3. setState로 데이터 갱신
응답받은 데이터는 setState 메서드를 통해 state에 저장합니다.
this.setState({
data: responseJson
})이제 this.state.data.body에 서버에서 받아온 데이터가 들어 있으므로, 이를 화면에 렌더링하면 됩니다.
render() {
return (
<View>
<Text>
{this.state.data.body}
</Text>
</View>
)
}전체 코드
fetch API를 사용해 서버에서 데이터를 가져오는 전체 코드는 다음과 같습니다.
import React, { Component } from "react";
import { Text, View } from "react-native";
class HttpExample extends Component {
state = {
data: ''
}
componentDidMount = () => { fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View>
<Text>
{this.state.data.body}
</Text>
</View>
)
}
}
const App = () => {
return (
<HttpExample />
)
}
export default App실행 결과
코드를 실행하면 서버에서 받아온 body 텍스트가 화면에 정상적으로 출력되는 것을 확인할 수 있습니다.

마무리
이처럼 React Native에서는 fetch API와 componentDidMount() 라이프사이클 메서드를 조합하면 간단하게 서버 데이터를 불러와 화면에 표시할 수 있습니다. 에러 처리를 위해 catch 블록을 반드시 함께 사용하는 것이 좋으며, POST 요청이나 헤더 설정이 필요한 경우 fetch의 두 번째 인자 옵션을 활용하면 됩니다.