fetch API

fetch API는 Ajax를 비동기형태로 쉽게 사용할 수 있는 api 함수이다. 

1
2
3
4
5
6
7
8
9
10
11
12
fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
})
.catch(function(err) {
console.log(err);
});


cs

URL을 인자로 받고 응답을 처리하기위한 Promise인 response 객체가 반환된다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ActivityIndicator} from 'react-native';
 
export default class App extends Component {
 
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null
    }
  }
 
  componentDidMount() {
    return fetch('https://facebook.github.io/react-native/movies.json')
            .then ( (response) => response.json() )
            .then( (responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.movies,
                })
            })
        .catch((error) => {
            console.log(error)
        });
  }
 
  render() {
      if (this.state.isLoading) {
        return (
            <View style={styles.container}>
                <ActivityIndicator />
            </View>
        )
    } else {
        let movies = this.state.dataSource.map((val, key) => {
            return <View key={key} style={styles.item}><Text>{val.title}</Text></View>
        });
        return (
            <View style={styles.container}>
                
                {movies}
            </View>
        );
    }
  }
}
 
const styles = StyleSheet.create({
  container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
  },
  item: {
      flex: 1,
      alignSelf: 'stretch',
      margin: 10,
      alignItems: 'center',
      justifyContent: 'center',
      borderBottomWidth: 1,
      borderBottomColor: '#eee'
  }
});
 
cs

[App.js]



map 함수 참고



원문 출처 : https://www.youtube.com/watch?v=hzLDsxPGctY

fetch api : https://blog.naver.com/dmswjd93/221273203218

https://medium.com/@kkak10/javascript-fetch-api-e26bfeaad9b6




블로그 이미지

클라인STR

,