[1] 자바스크립이 제공하는 XMLHttpRequest 사용해 통신하기
🔨 사용방법
- 네크워크작업 객체 생성 : XMLHttpRequest (안드는 : httpRequst)
- 서버 응답결과 받을 때 반응하는 콜백메소드 등록 - 이 작업은 반드시 send 하기 전에 쓰는 걸 권장 : onreadystatechange
- 무지개 로드(스트림) 열기 : .open()
- 보내기 : .send()
import React, { useState } from "react";
import { View, Text, Button, StyleSheet, ScrollView, Alert } from "react-native";
export default function main():JSX.Element {
const [message , setMessage] = useState('message....')
const fetchData = () => {
console.log('fetch start')
const Xhr = new XMLHttpRequest()
Xhr.onreadystatechange = () => {
if( Xhr.readyState == 4 && Xhr.status == 200) {
Alert.alert('응답 완료')
setMessage( Xhr.responseText )
}
}
Xhr.open('GET','http://mrhisj23.dothome.co.kr/', true)
Xhr.send()
}
return(
<View style={style.root}>
<Button title="fetch data from network" onPress={fetchData}></Button>
<ScrollView style={style.container}>
<Text style={style.text}> {message} </Text>
</ScrollView>
</View>
)
}
const style = StyleSheet.create({
root: {
flex : 1,
padding : 16,
},
container : {
marginTop : 16,
},
text : {
padding : 8,
color : 'black',
}
})
[2] fetch 라이브러리 사용하기
import React, { useState } from "react";
import { View, Text, Button, StyleSheet, ScrollView, Alert } from "react-native";
export default function main():JSX.Element {
const [message , setMessage] = useState('message....')
type movieInfo = {
id :string,
title : string,
releaseYear : string
}
type MoviesResponse = {
title:string,
description : string,
movies : movieInfo[]
}
const [moviesResponse, setMoviesResponse] = useState<MoviesResponse>({title:"", description:"", movies: []})
const fetchData = () => {
fetch('http://mrhisj23.dothome.co.kr/index.js')
.then((response:Response) => Alert.alert(response.status.toString()))
fetch('http://mrhisj23.dothome.co.kr/index.js')
.then((respose:Response) => {
return respose.text()
}).then((text : string) => {
setMessage(text)
}).catch((error)=>{
Alert.alert(error)
})
fetch('http://mrhisj23.dothome.co.kr/')
.then(response => response.text())
.then(text => setMessage(text))
}
return(
<View style={style.root}>
<Button title="fetch data from network" onPress={fetchData}></Button>
<ScrollView style={style.container}>
<Text style={style.text}> {message} </Text>
</ScrollView>
{}
<View style={{flex :1, marginTop:16}}>
<Text style={{color:'black', fontWeight:"bold", padding: 8}}>{moviesResponse.title}</Text>
{}
{
moviesResponse.movies.map( (movie : movieInfo, index) => {
return (
<View style={style.item} key={index}>
<Text>{movie.id}</Text>
<Text>{movie.title}</Text>
<Text>{movie.releaseYear}</Text>
</View>
)
} )
}
</View>
</View>
)
}
const style = StyleSheet.create({
root: {
flex : 1,
padding : 16,
},
container : {
marginTop : 16,
},
text : {
padding : 8,
color : 'black',
},
item : {
borderWidth : 1,
borderRadius : 3,
padding : 8,
margin : 2,
}
})
[3] OPEN API 파싱
1. 우선 페이스북에서 샘플로 제공하는 json 파싱 실습
1.1) 우선 텍스트로 보여주기
import React, { useState } from "react";
import { View, Text, Button, StyleSheet, ScrollView, Alert } from "react-native";
export default function main():JSX.Element {
const [message , setMessage] = useState('message....')
const fetchData = () => {
console.log('fetch start')
fetch('https://reactnative.dev/movies.json')
.then(res => res.text())
.then(text => setMessage(text))
}
return(
<View style={style.root}>
<Button title="fetch data from network" onPress={fetchData}></Button>
<ScrollView style={style.container}>
<Text style={style.text}> {message} </Text>
</ScrollView>
</View>
)
}
const style = StyleSheet.create({
root: {
flex : 1,
padding : 16,
},
container : {
marginTop : 16,
},
text : {
padding : 8,
color : 'black',
}
})
1.2) 분석하기
- json 파싱하기
import React, { useState } from "react";
import { View, Text, Button, StyleSheet, ScrollView, Alert } from "react-native";
export default function main():JSX.Element {
const [message , setMessage] = useState('message....')
type movieInfo = {
id :string,
title : string,
releaseYear : string
}
type MoviesResponse = {
title:string,
description : string,
movies : movieInfo[]
}
const [moviesResponse, setMoviesResponse] = useState<MoviesResponse>({title:"", description:"", movies: []})
const fetchData = () => {
fetch('https://reactnative.dev/movies.json')
.then(res => res.json())
.then(obj => setMoviesResponse(obj) )
let name = "dam"
let message = "ok"
fetch(`http://mrhisj23.dothome.co.kr/get_aaa.php?name=${name}&message=${message}`)
.then(res => res.text())
.then(text => setMessage(text))
fetch(`http://mrhisj23.dothome.co.kr/post_bbb.php`, {
method : 'POST',
headers : {'content-type':'application/x-www-form-urlecoded'},
body : `name=${name}&message=${message}`,
}).then(res => res.text()).then(text => setMessage(text))
let person = {name : "dam", age : 20}
fetch(`http://mrhisj23.dothome.co.kr/post_bbb.php`, {
method : 'POST',
headers : {'content-type':'application/json'},
body : JSON.stringify(person)
}).then(res => res.json).then(obj => Alert.alert('제이슨 파싱 객체 받음' + obj))
}
return(
<View style={style.root}>
<Button title="fetch data from network" onPress={fetchData}></Button>
<ScrollView style={style.container}>
<Text style={style.text}> {message} </Text>
</ScrollView>
{}
<View style={{flex :1, marginTop:16}}>
<Text style={{color:'black', fontWeight:"bold", padding: 8}}>{moviesResponse.title}</Text>
{}
{
moviesResponse.movies.map( (movie : movieInfo, index) => {
return (
<View style={style.item} key={index}>
<Text>{movie.id}</Text>
<Text>{movie.title}</Text>
<Text>{movie.releaseYear}</Text>
</View>
)
} )
}
</View>
</View>
)
}
const style = StyleSheet.create({
root: {
flex : 1,
padding : 16,
},
container : {
marginTop : 16,
},
text : {
padding : 8,
color : 'black',
},
item : {
borderWidth : 1,
borderRadius : 3,
padding : 8,
margin : 2,
}
})