expo, local api 불러오기 오류

값이 나오지 않는데 아무런 오류 메세지가 없어서 해결을 못하고 있습니다.

조언부탁드립니다…

App.js

import React, { Component } from 'react';
import {
  Text,
  View,
  TextInput,
  Button,
  StyleSheet

} from "react-native";
import Client from './Client.js';



class App extends Component {

  constructor() {
    super()
    this.state = {
      users: [] // user에 대한 정보를 담기 위한 state
    }
    this.handleUserInputChange = this.handleUserInputChange.bind(this)
  }

  componentWillMount = () => {
    this.getUser()
  }

  handleUserInputChange = event => {
    const {target: {name, value}} = event
    this.setState({
      [name]: value
    });
  }

  getUser = async() => {
    try{
    Client.search('User') // Client.js에서 
    .then(data => {
      this.setState({
        users: data 
      })
    })}
    catch(error){
      console.error(error);
    }
  }
  


  submitUser = () => {
    try {
      const data = {
      "$class": "org.acme.model.User",
      "phonenumber": this.state.phonenumber,
      "email": this.state.email,
      "firstName": this.state.firstName,
      "lastName": this.state.lastName,

    }

    Client.create('User', data)
    .then(() => {
      this.getUser()
    })
  } catch(error){
    console.error(error);
  }
}

  render() {
    return(
      <View className="App">
        <Text>Add User</Text>
        <Text>phonenumber:</Text>
        <TextInput 
          onChange={this.handleUserInputChange}
          type="text"
          name="phonenumber" />
        <Text>email:</Text>
        <TextInput
          onChange={this.handleUserInputChange}
          type="text"
          name="email" />
        <Text>firstName:</Text>
        <TextInput 
          onChange={this.handleUserInputChange}
          type="text"
          name="firstName" />
        <Text>lastName:</Text>
        <TextInput 
          onChange={this.handleUserInputChange}
          type="text"
          name="lastName" />

        <Button title="New User" onPress={()=> this.submitUser}/>
    


        <View style={styles.container}>
          <Text style={styles.userlist}>
            User List
          </Text>
          {this.state.users.map((r, i) => (
            <View style={styles.userstate}
                  key={i}>
          <Text>phonenumber: {r.phonenumber}</Text>
          <Text>email: {r.email}</Text>
          <Text>firstName: {r.firstName}</Text>
          <Text>lastName: {r.lastName}</Text>
        </View>
          ))}
      </View>
    </View>
    )
  }
}

const styles=StyleSheet.create({
  container: {
    flex:1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  userlist:{
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  userstate:{
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

export default App;

Client.js

const search = async(type) => {
    try{ let response = await fetch(`http://localhost:3000/api/${type}`, {
        accept: 'application/json'
    });
    let result = await response.json();
    return result;
    } catch (error){
        console.error(error);
    }  
}



const create = async(type, data) => {
    try{
    let response = await fetch(`http://localhost:3000/api/${type}`, {
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: 'post',
        body: JSON.stringify(data)
    });
    let result = await response.json();
    return result;
    } catch (error){
        console.error(error);
    }
}

const Client = {search, create};
export default Client;

localhost:3000에서 user가 띄워지는 것은 확인하였는데 아래와 같이expo에서 실행하면 값이 불러오지 않습니다.

일단 await 부분을 try catch로 감싸주세요. 에러 처리를 하셔야 합니다.

1개의 좋아요


동일한 오류가 발생했는데 어디가 문제있는지 알수있을까요??

JSON.stringify()에 then을 왜 다세요? then 과 catch를 잘못 다신것 같고요. try catch는 await을 감싸야 합니다.

1개의 좋아요

게시물 수정하였는데 조언 부탁드려도 될까요??

일단 아래 코드가 예외처리가 되지 않고 있습니다. Promise를 try catch로는 예외처리가 안됩니다. .catch()를 이용하거나 Promise 앞에 await을 붙여서 예외 발생시 throw가 되도록 해야 try catch로 예외 처리가 가능합니다.

 getUser = async() => {
    try{
    Client.search('User') // Client.js에서 
    .then(data => {
      this.setState({
        users: data 
      })
    })}
    catch(error){
      console.error(error);
    }
  }

일단 위 부분만 봤을 때 저라면 다음과 같이 작성하겠습니다.

 getUser = () => {
    return Client.search('User')
    .then(data => {
      this.setState({
        users: data 
      })
    })
    .catch(error){
      console.error(error);
    }
  }

먼저 비동기, Promise, Async/Await에 대해 차분히 살펴보실 필요가 있습니다.
먼저 댓글달아주신 @ZeroCho 님의 블로그유튜브에도 유익한 정보가 많습니다.

코드종 유튜브 채널에도 이와 관련된 영상도 있으니 한번 살펴보세요.

그리고 본문을 수정하기보다는 댓글로 이어서 달아주세요. 그래야 글의 내용을 다른사람들이 봤을 때 이해하기 쉽고 기록으로 남게되어 비슷한 문제를 겪었던 분들에게 도움이 됩니다. :slight_smile: :pray:

감사합니다! 덕분에 해결하였습니다