Rest-Server & React-native에서 PUT 방식으로 기존 데이터를 변경하고 싶습니다

fetchGradeUpdate() {
const itemId = this.props.navigation.getParam(‘itemId’);
const adminId= this.props.navigation.getParam(‘adminId’);
console.log(itemId);
console.log(adminId);
return fetch(http://192.168.190.16:3000/api/Grade/${itemId},
{

    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    method: 'PUT',
    body: JSON.stringify({
      
        $class: "org.acme.model.Grade",
        safetycheck_date: this.state.safetycheck_date,
        facilityNumber: [], 
        admin: `${adminId}`,
        Electricity: this.state.Electricity,
        Gas: this.state.Gas,
        Elevator: this.state.Elevator,
        Earthquake_resistant: this.state.Earthquake_resistant,
        Final: this.state.Final

    })
  })
  .then(response => response.json())
  .catch(error => {
    console.error(error);
  });

render() {
return(

    <Text>safetycheck_date_update</Text>
    <TextInput 
      onChangeText={(text) => { this.setState({ safetycheck_date : text }) }}></TextInput>
    <Text>Electricity_Grade_update</Text>
    <TextInput 
      onChangeText={(text) => { this.setState({ Electricity : text }) }}></TextInput>
    <Button title="+ GradeUpdate"
      onPress={() => { this.fetchGradeUpdate().then(() => { this.props.navigation.navigate('GradeScreen') }) }}>
    </Button>

  </View>
)

Post방식과 Get방식으로 데이터를 불러들이거나 생성하는것은 성공했지만 기존 데이터를 변경하는 Put방식은 어떻게 해야 하는지 잘 모르겠습니다…
getParam로 불러온 itemId와 adminId 값은 console 로그로 넘겨지는것을 확인한 상태입니다.
ㅠ 도와주세요

post랑 put delete patch는 사용 방법이 같습니다. method만 바꿔 보내시면 되는데 어떤 문제가 있으신 건가요? 서버에서 라우터도 put용으로 만드셨죠?

제가 지금 Hyperledger Composer rest server를 이용중이고 PUT 방식은 Post, Get방식과 다르게 parameter가 요구되더라고요. 캡처화면 참고부탁드립니다.

%EC%BA%A1%EC%B2%982

catch로 설정해 둔 Error로그가 안 찍혔나요?

댓글에 남기신 캡쳐에는 facilityNumber가 string인데 위 코드에서는 빈 배열이네요. 타입 에러일겁니다.

에러로그를 꼭 확인해보세요. 기본적인 에러는
대부분 로그에 나올 겁니다.

안녕하세요, PUT 방식을 rest-server 형식에 맞춰서 넣었을때는 데이터가 바뀌었습니다.

fetchGradeUpdate() {

return fetch(`http://192.168.190.16:3000/api/Grade/1`,
  {
    
    headers: {
      'Accept': 'application/json',
      "date": "Thu, 10 Jan 2019 03:00:17 GMT",
      "x-content-type-options": "nosniff",
      "etag": "W/\"e2-kYVVz5gED3yKO/9HE+gjuOt5AZ4\"",
      "x-download-options": "noopen",
      "x-frame-options": "DENY",
      "Content-type": "application/json; charset=utf-8",
      "access-control-allow-origin": "http://localhost:3000",
      "access-control-allow-credentials": "true",
      "connection": "keep-alive",
      "vary": "Origin, Accept-Encoding",
      "content-length": "226",
      "x-xss-protection": "1; mode=block"
    },
    method: 'PUT',
    body: JSON.stringify({
      
        $class: "org.acme.model.Grade",
        safetycheck_date: "2019.01.10",
        admin: "resource:org.acme.model.User#[email protected]",
        Electricity: "Green",
        Gas: "Green",
        Elevator: "Green",
        Earthquake_resistant: "Green",
        Final: "Green"

    })
  })
  .then(response => {
    response.json(),
    console.log(response.json())
  })
  .catch(error => {
    console.error(error);
  });

%EC%BA%A1%EC%B2%98

그런데, body안의 내용을 this.state로 바꾸고 render 함수에서 TextInput 라이브러리를 써서 onChangeText에 setState를 함으로서 데이터를 바꾸었을 때는 데이터가 넘어가지가 않습니다.

return fetch(`http://192.168.190.16:3000/api/Grade/${facilityNumber_prev}`,
  {
    
    headers: {
      'Accept': 'application/json',
      "date": "Thu, 10 Jan 2019 03:00:17 GMT",
      "x-content-type-options": "nosniff",
      "etag": "W/\"e2-kYVVz5gED3yKO/9HE+gjuOt5AZ4\"",
      "x-download-options": "noopen",
      "x-frame-options": "DENY",
      "Content-type": "application/json; charset=utf-8",
      "access-control-allow-origin": "http://localhost:3000",
      "access-control-allow-credentials": "true",
      "connection": "keep-alive",
      "vary": "Origin, Accept-Encoding",
      "content-length": "226",
      "x-xss-protection": "1; mode=block"
    },
    method: 'PUT',
    body: JSON.stringify({
      
        $class: "org.acme.model.Grade",
        safetycheck_date: this.state.safetycheck_date,
        admin: "resource:org.acme.model.User#[email protected]",
        Electricity: this.state.Electricity,
        Gas: this.state.Gas,
        Elevator: this.state.Elvator,
        Earthquake_resistant: this.state.Earthquake_resistant,
        Final: this.state.Final

    })
  })
  .then(response => {
    response.json(),
    console.log(response.json())
  })
  .catch(error => {
    console.error(error);
  });

render() {

return(
    <View style={styles1.container}> 
    
    <View Update Electricity ></View>
    
    <Text>safetycheck_date_update</Text>
    <TextInput 
      value={this.state.safetycheck_date} onChangeText={(text) => { this.setState({ safetycheck_date : text }) }}></TextInput>
    <Text>Electricity_Grade_update</Text>
    <TextInput 
      value={this.state.Electricity} onChangeText={(text) => { this.setState({ Electricity : text }) }}></TextInput>
    <TextInput 
     value={this.state.Gas} onChangeText={(text) => { this.setState({ Gas : text }) }}></TextInput>
    <TextInput 
     value={this.state.Elevator} onChangeText={(text) => { this.setState({ Elevator : text }) }}></TextInput>
    <TextInput 
     value={this.state.Earthquake_resistant} onChangeText={(text) => { this.setState({ Earthquake_resistant : text }) }}></TextInput>
    <TextInput 
     value={this.state.Final} onChangeText={(text) => { this.setState({ Final : text }) }}></TextInput>
    <Button title="+ GradeUpdate"
      onPress={() => { this.fetchGradeUpdate().then(() => { this.props.navigation.navigate('GradeScreen') }) }}>
    </Button>

  </View>

Put방식으로 데이터를 바꿀 때는 TextInput으로 onChangeText를 쓰면 안되는건가요? 다른 handleChange를 써야하는지… 잘 모르겠습니다 ㅠ

fetch 함수 안 json response 에러는 [Unhandled promise rejection: TypeError: Already read] 이라고 뜹니다. 이종은 강사님 말씀대로 Type Error인거 같은데 어떤게 문제인지…ㅠ

Already read 에러

이미 찾아보셨을 수도 있지만 에러가 나오면 우선 에러를 구글 검색으로 찾아보시길 추천합니다.
말씀하신 [Unhandled promise rejection: TypeError: Already read]는 검색해보면 쉽게 찾을 수 있는 에러입니다. 이미 response를 읽어서 json으로 변형했는데 다시 json을 호출해서 생기는 문제입니다.

Promise의 잘못된 사용

.then(response => {
    response.json(),
    console.log(response.json())
  })

위 코드에서 then으로 넘긴 함수는 아무것도 리턴하지 않으므로 fetchGradeUpdate에다가 then을 붙이면 아무런 값도 얻을 수 없습니다.

코드 삽입시 markdown을 이용

질문에 코드를 올릴 때는 markdown의 code 문법을 이용하면 보다 보기 쉽게 코드를 올릴 수 있습니다. 다음 글을 참고하여 코드를 넣으시면 다른 분들이 읽기 편합니다. :slight_smile: 다른 분들이 읽기 편해야 보다 정확한 답변을 들을 수 있습니다.

PUT으로 데이터를 보내는 것과 setState의 아무 관계 없습니다.

state값이 정상적으로 들어가지 않아서 put할 때 undefined 같은 값으로 전달된건 아닌지 확인해보세요.