react native: empty state when try to fetch











up vote
1
down vote

favorite












I'm new in react native and I guess that probably miss something very simple but I read many previous questions and did not get my answer. I'm trying to fetch POST request with my data that I can render or print in the console exactly before the fetch function but when it sent the data it is null on the server. If I try with hardcore values directly into the fetch function it works well.



export default class CreateNewPostScreen extends React.Component {
constructor(props){
super(props)

this.state = {
source: '',
description: '',
location: '',
token: ''
}
}

static navigationOptions = {
title: 'Create New Post'
}

componentWillMount() {
AsyncStorage.getItem("userToken").then((value) => {
this.setState({
//Getting data from prev screen(ProfileScreen)
source: this.props.navigation.state.params.newPostBase64Image,
token: value
})
}).done()
}

_fetchCreateNewPost = async () => {
fetch(baseUrl + 'api/profile/CreateNewPost',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
Authorization: this.state.token
},
body: JSON.stringify({
Date: new Date(),
Description: this.state.description,
Location: this.state.location,
SourcePath: this.state.source
}),
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}

render() {
return(
<ScrollView style={{backgroundColor: 'white'}}>
<View style={styles.agreementField}>
<View>
<TouchableOpacity>
<Text style={styles.escBtn} onPress={() => this.props.navigation.navigate('Profile')}>X</Text>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={this._fetchCreateNewPost}>
<Text style={styles.acceptBtn}>✓</Text>
</TouchableOpacity>
</View>
</View>
<View style={styles.container}>
<View style={{padding:5}}>
<Image
style={styles.image}
source={{uri:`data:image/png;base64,${this.state.source}`}}
/>
</View>
<View style={styles.textAreaContainer} >
<TextInput
style={styles.textArea}
underlineColorAndroid="transparent"
placeholder="Type something"
placeholderTextColor="grey"
numberOfLines={1}
multiline={true}
onChangeText={(text) => this.setState({description:text})}
/>
</View>
</View>
<View>
<View>
<TextInput
style={styles.input}
placeholder="Location"
underlineColorAndroid= '#C0C0C0'
onChangeText={(text) => this.setState({location:text})}
/>
</View>
</View>
</ScrollView>
)
}
}









share|improve this question


























    up vote
    1
    down vote

    favorite












    I'm new in react native and I guess that probably miss something very simple but I read many previous questions and did not get my answer. I'm trying to fetch POST request with my data that I can render or print in the console exactly before the fetch function but when it sent the data it is null on the server. If I try with hardcore values directly into the fetch function it works well.



    export default class CreateNewPostScreen extends React.Component {
    constructor(props){
    super(props)

    this.state = {
    source: '',
    description: '',
    location: '',
    token: ''
    }
    }

    static navigationOptions = {
    title: 'Create New Post'
    }

    componentWillMount() {
    AsyncStorage.getItem("userToken").then((value) => {
    this.setState({
    //Getting data from prev screen(ProfileScreen)
    source: this.props.navigation.state.params.newPostBase64Image,
    token: value
    })
    }).done()
    }

    _fetchCreateNewPost = async () => {
    fetch(baseUrl + 'api/profile/CreateNewPost',{
    method: 'POST',
    headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    Authorization: this.state.token
    },
    body: JSON.stringify({
    Date: new Date(),
    Description: this.state.description,
    Location: this.state.location,
    SourcePath: this.state.source
    }),
    })
    .then((response) => {
    console.log(response)
    })
    .catch((error) => {
    console.log(error)
    })
    }

    render() {
    return(
    <ScrollView style={{backgroundColor: 'white'}}>
    <View style={styles.agreementField}>
    <View>
    <TouchableOpacity>
    <Text style={styles.escBtn} onPress={() => this.props.navigation.navigate('Profile')}>X</Text>
    </TouchableOpacity>
    </View>
    <View>
    <TouchableOpacity onPress={this._fetchCreateNewPost}>
    <Text style={styles.acceptBtn}>✓</Text>
    </TouchableOpacity>
    </View>
    </View>
    <View style={styles.container}>
    <View style={{padding:5}}>
    <Image
    style={styles.image}
    source={{uri:`data:image/png;base64,${this.state.source}`}}
    />
    </View>
    <View style={styles.textAreaContainer} >
    <TextInput
    style={styles.textArea}
    underlineColorAndroid="transparent"
    placeholder="Type something"
    placeholderTextColor="grey"
    numberOfLines={1}
    multiline={true}
    onChangeText={(text) => this.setState({description:text})}
    />
    </View>
    </View>
    <View>
    <View>
    <TextInput
    style={styles.input}
    placeholder="Location"
    underlineColorAndroid= '#C0C0C0'
    onChangeText={(text) => this.setState({location:text})}
    />
    </View>
    </View>
    </ScrollView>
    )
    }
    }









    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I'm new in react native and I guess that probably miss something very simple but I read many previous questions and did not get my answer. I'm trying to fetch POST request with my data that I can render or print in the console exactly before the fetch function but when it sent the data it is null on the server. If I try with hardcore values directly into the fetch function it works well.



      export default class CreateNewPostScreen extends React.Component {
      constructor(props){
      super(props)

      this.state = {
      source: '',
      description: '',
      location: '',
      token: ''
      }
      }

      static navigationOptions = {
      title: 'Create New Post'
      }

      componentWillMount() {
      AsyncStorage.getItem("userToken").then((value) => {
      this.setState({
      //Getting data from prev screen(ProfileScreen)
      source: this.props.navigation.state.params.newPostBase64Image,
      token: value
      })
      }).done()
      }

      _fetchCreateNewPost = async () => {
      fetch(baseUrl + 'api/profile/CreateNewPost',{
      method: 'POST',
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      Authorization: this.state.token
      },
      body: JSON.stringify({
      Date: new Date(),
      Description: this.state.description,
      Location: this.state.location,
      SourcePath: this.state.source
      }),
      })
      .then((response) => {
      console.log(response)
      })
      .catch((error) => {
      console.log(error)
      })
      }

      render() {
      return(
      <ScrollView style={{backgroundColor: 'white'}}>
      <View style={styles.agreementField}>
      <View>
      <TouchableOpacity>
      <Text style={styles.escBtn} onPress={() => this.props.navigation.navigate('Profile')}>X</Text>
      </TouchableOpacity>
      </View>
      <View>
      <TouchableOpacity onPress={this._fetchCreateNewPost}>
      <Text style={styles.acceptBtn}>✓</Text>
      </TouchableOpacity>
      </View>
      </View>
      <View style={styles.container}>
      <View style={{padding:5}}>
      <Image
      style={styles.image}
      source={{uri:`data:image/png;base64,${this.state.source}`}}
      />
      </View>
      <View style={styles.textAreaContainer} >
      <TextInput
      style={styles.textArea}
      underlineColorAndroid="transparent"
      placeholder="Type something"
      placeholderTextColor="grey"
      numberOfLines={1}
      multiline={true}
      onChangeText={(text) => this.setState({description:text})}
      />
      </View>
      </View>
      <View>
      <View>
      <TextInput
      style={styles.input}
      placeholder="Location"
      underlineColorAndroid= '#C0C0C0'
      onChangeText={(text) => this.setState({location:text})}
      />
      </View>
      </View>
      </ScrollView>
      )
      }
      }









      share|improve this question













      I'm new in react native and I guess that probably miss something very simple but I read many previous questions and did not get my answer. I'm trying to fetch POST request with my data that I can render or print in the console exactly before the fetch function but when it sent the data it is null on the server. If I try with hardcore values directly into the fetch function it works well.



      export default class CreateNewPostScreen extends React.Component {
      constructor(props){
      super(props)

      this.state = {
      source: '',
      description: '',
      location: '',
      token: ''
      }
      }

      static navigationOptions = {
      title: 'Create New Post'
      }

      componentWillMount() {
      AsyncStorage.getItem("userToken").then((value) => {
      this.setState({
      //Getting data from prev screen(ProfileScreen)
      source: this.props.navigation.state.params.newPostBase64Image,
      token: value
      })
      }).done()
      }

      _fetchCreateNewPost = async () => {
      fetch(baseUrl + 'api/profile/CreateNewPost',{
      method: 'POST',
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      Authorization: this.state.token
      },
      body: JSON.stringify({
      Date: new Date(),
      Description: this.state.description,
      Location: this.state.location,
      SourcePath: this.state.source
      }),
      })
      .then((response) => {
      console.log(response)
      })
      .catch((error) => {
      console.log(error)
      })
      }

      render() {
      return(
      <ScrollView style={{backgroundColor: 'white'}}>
      <View style={styles.agreementField}>
      <View>
      <TouchableOpacity>
      <Text style={styles.escBtn} onPress={() => this.props.navigation.navigate('Profile')}>X</Text>
      </TouchableOpacity>
      </View>
      <View>
      <TouchableOpacity onPress={this._fetchCreateNewPost}>
      <Text style={styles.acceptBtn}>✓</Text>
      </TouchableOpacity>
      </View>
      </View>
      <View style={styles.container}>
      <View style={{padding:5}}>
      <Image
      style={styles.image}
      source={{uri:`data:image/png;base64,${this.state.source}`}}
      />
      </View>
      <View style={styles.textAreaContainer} >
      <TextInput
      style={styles.textArea}
      underlineColorAndroid="transparent"
      placeholder="Type something"
      placeholderTextColor="grey"
      numberOfLines={1}
      multiline={true}
      onChangeText={(text) => this.setState({description:text})}
      />
      </View>
      </View>
      <View>
      <View>
      <TextInput
      style={styles.input}
      placeholder="Location"
      underlineColorAndroid= '#C0C0C0'
      onChangeText={(text) => this.setState({location:text})}
      />
      </View>
      </View>
      </ScrollView>
      )
      }
      }






      react-native






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 9 at 22:55









      Stoycho Mihaylov Mihaylov

      62




      62
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          the body must be a JSON, not a string. JSON.stringify() returns a string.



          I think you must change your code to this(some other things I changed):



          Your _fetchCreateNewPost function:



          _fetchCreateNewPost = () => {
          return fetch(baseUrl + 'api/profile/CreateNewPost',{
          method: 'POST',
          headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          Authorization: this.state.token
          },
          body: {
          Date: new Date(),
          Description: this.state.description,
          Location: this.state.location,
          SourcePath: this.state.source
          },
          })
          .then(response => response.json())
          .then(data => {
          console.log(data)
          })
          .catch((error) => {
          console.log(error)
          })
          }


          onPress of TouchableOpacity that uses _fetchCreateNewPost:



          <TouchableOpacity onPress={()=>this._fetchCreateNewPost()}>
          <Text style={styles.acceptBtn}>✓</Text>
          </TouchableOpacity>





          share|improve this answer





















          • When change it like this I receive "unsupported BodyInit type" and my others screens use JSON.stringify() and work well
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:40










          • keep using JSON.stringify() and apply my other changes
            – Hameda169
            Nov 9 at 23:43












          • I tried but still nothing changes...
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:56










          • I'm trying to transfer image as base64 string format in SourcePath, is this possibly the problem ? Because the string is too long
            – Stoycho Mihaylov Mihaylov
            Nov 10 at 21:00











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234300%2freact-native-empty-state-when-try-to-fetch%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote













          the body must be a JSON, not a string. JSON.stringify() returns a string.



          I think you must change your code to this(some other things I changed):



          Your _fetchCreateNewPost function:



          _fetchCreateNewPost = () => {
          return fetch(baseUrl + 'api/profile/CreateNewPost',{
          method: 'POST',
          headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          Authorization: this.state.token
          },
          body: {
          Date: new Date(),
          Description: this.state.description,
          Location: this.state.location,
          SourcePath: this.state.source
          },
          })
          .then(response => response.json())
          .then(data => {
          console.log(data)
          })
          .catch((error) => {
          console.log(error)
          })
          }


          onPress of TouchableOpacity that uses _fetchCreateNewPost:



          <TouchableOpacity onPress={()=>this._fetchCreateNewPost()}>
          <Text style={styles.acceptBtn}>✓</Text>
          </TouchableOpacity>





          share|improve this answer





















          • When change it like this I receive "unsupported BodyInit type" and my others screens use JSON.stringify() and work well
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:40










          • keep using JSON.stringify() and apply my other changes
            – Hameda169
            Nov 9 at 23:43












          • I tried but still nothing changes...
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:56










          • I'm trying to transfer image as base64 string format in SourcePath, is this possibly the problem ? Because the string is too long
            – Stoycho Mihaylov Mihaylov
            Nov 10 at 21:00















          up vote
          0
          down vote













          the body must be a JSON, not a string. JSON.stringify() returns a string.



          I think you must change your code to this(some other things I changed):



          Your _fetchCreateNewPost function:



          _fetchCreateNewPost = () => {
          return fetch(baseUrl + 'api/profile/CreateNewPost',{
          method: 'POST',
          headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          Authorization: this.state.token
          },
          body: {
          Date: new Date(),
          Description: this.state.description,
          Location: this.state.location,
          SourcePath: this.state.source
          },
          })
          .then(response => response.json())
          .then(data => {
          console.log(data)
          })
          .catch((error) => {
          console.log(error)
          })
          }


          onPress of TouchableOpacity that uses _fetchCreateNewPost:



          <TouchableOpacity onPress={()=>this._fetchCreateNewPost()}>
          <Text style={styles.acceptBtn}>✓</Text>
          </TouchableOpacity>





          share|improve this answer





















          • When change it like this I receive "unsupported BodyInit type" and my others screens use JSON.stringify() and work well
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:40










          • keep using JSON.stringify() and apply my other changes
            – Hameda169
            Nov 9 at 23:43












          • I tried but still nothing changes...
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:56










          • I'm trying to transfer image as base64 string format in SourcePath, is this possibly the problem ? Because the string is too long
            – Stoycho Mihaylov Mihaylov
            Nov 10 at 21:00













          up vote
          0
          down vote










          up vote
          0
          down vote









          the body must be a JSON, not a string. JSON.stringify() returns a string.



          I think you must change your code to this(some other things I changed):



          Your _fetchCreateNewPost function:



          _fetchCreateNewPost = () => {
          return fetch(baseUrl + 'api/profile/CreateNewPost',{
          method: 'POST',
          headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          Authorization: this.state.token
          },
          body: {
          Date: new Date(),
          Description: this.state.description,
          Location: this.state.location,
          SourcePath: this.state.source
          },
          })
          .then(response => response.json())
          .then(data => {
          console.log(data)
          })
          .catch((error) => {
          console.log(error)
          })
          }


          onPress of TouchableOpacity that uses _fetchCreateNewPost:



          <TouchableOpacity onPress={()=>this._fetchCreateNewPost()}>
          <Text style={styles.acceptBtn}>✓</Text>
          </TouchableOpacity>





          share|improve this answer












          the body must be a JSON, not a string. JSON.stringify() returns a string.



          I think you must change your code to this(some other things I changed):



          Your _fetchCreateNewPost function:



          _fetchCreateNewPost = () => {
          return fetch(baseUrl + 'api/profile/CreateNewPost',{
          method: 'POST',
          headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          Authorization: this.state.token
          },
          body: {
          Date: new Date(),
          Description: this.state.description,
          Location: this.state.location,
          SourcePath: this.state.source
          },
          })
          .then(response => response.json())
          .then(data => {
          console.log(data)
          })
          .catch((error) => {
          console.log(error)
          })
          }


          onPress of TouchableOpacity that uses _fetchCreateNewPost:



          <TouchableOpacity onPress={()=>this._fetchCreateNewPost()}>
          <Text style={styles.acceptBtn}>✓</Text>
          </TouchableOpacity>






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 9 at 23:20









          Hameda169

          1087




          1087












          • When change it like this I receive "unsupported BodyInit type" and my others screens use JSON.stringify() and work well
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:40










          • keep using JSON.stringify() and apply my other changes
            – Hameda169
            Nov 9 at 23:43












          • I tried but still nothing changes...
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:56










          • I'm trying to transfer image as base64 string format in SourcePath, is this possibly the problem ? Because the string is too long
            – Stoycho Mihaylov Mihaylov
            Nov 10 at 21:00


















          • When change it like this I receive "unsupported BodyInit type" and my others screens use JSON.stringify() and work well
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:40










          • keep using JSON.stringify() and apply my other changes
            – Hameda169
            Nov 9 at 23:43












          • I tried but still nothing changes...
            – Stoycho Mihaylov Mihaylov
            Nov 9 at 23:56










          • I'm trying to transfer image as base64 string format in SourcePath, is this possibly the problem ? Because the string is too long
            – Stoycho Mihaylov Mihaylov
            Nov 10 at 21:00
















          When change it like this I receive "unsupported BodyInit type" and my others screens use JSON.stringify() and work well
          – Stoycho Mihaylov Mihaylov
          Nov 9 at 23:40




          When change it like this I receive "unsupported BodyInit type" and my others screens use JSON.stringify() and work well
          – Stoycho Mihaylov Mihaylov
          Nov 9 at 23:40












          keep using JSON.stringify() and apply my other changes
          – Hameda169
          Nov 9 at 23:43






          keep using JSON.stringify() and apply my other changes
          – Hameda169
          Nov 9 at 23:43














          I tried but still nothing changes...
          – Stoycho Mihaylov Mihaylov
          Nov 9 at 23:56




          I tried but still nothing changes...
          – Stoycho Mihaylov Mihaylov
          Nov 9 at 23:56












          I'm trying to transfer image as base64 string format in SourcePath, is this possibly the problem ? Because the string is too long
          – Stoycho Mihaylov Mihaylov
          Nov 10 at 21:00




          I'm trying to transfer image as base64 string format in SourcePath, is this possibly the problem ? Because the string is too long
          – Stoycho Mihaylov Mihaylov
          Nov 10 at 21:00


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234300%2freact-native-empty-state-when-try-to-fetch%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini