1

I am trying to put fetch functions into a separated file, so I can organise these API fetch easily. However, when I try to fetch and return the data, it gives me null or an unexpected json object. Here is part of my src:

//api.js
export async function LoginAPI(username, password) {
   const url = baseURL + "/login/";
   var params = {username: username, password: md5.hex_md5(password)};

   let response = await fetch(url, {
      method: 'POST',
      headers: {'Accept': 'application/json','Content-Type': 'application/x-www-form-urlencoded'},
      body: JSON.stringify(params)
   });
   return await fetch(url, {
      method: 'POST',
      headers: header,
      body: JSON.stringify(params)
   })
   .then((res) => res.text())
   .then((text) => text.length ? JSON.parse(text) : {})
    .catch((error) => {
        throw error;
    });
};

Here is the another file.

//index.js
var Login = React.createClass({
  onPress_login: function() {
  var value = this.refs.form.getValue();
  if (value) {
     result = LoginAPI(value.username, value.password);
     console.log(result);
  } else {
     this.AlertDialog.openDialog();
  }
},
render() {
   return (
 (...)
 <Button onPress={this.onPress_login}>
     <Text>Login</Text>
 </Button>

The fetch is working, it is communicating with the server. However, the console log returns me this at the first place

 Promise  _45: 0_54: null  _65: null  _81: 1  __proto__: Object

I am assuming that the result log in the console at the first place is not the await result (the actual response from server, but an object of fetch response). I tried to search out methods online but I can't find any post/blog/article saying how to do fetch as a function call.

Is there any way to do like swift, LoginAPI(username, password, callback: {...}) please?

1 Answer 1

5

The problem is that you're are making an async function and not waiting for the response, the you see that kind of console log.

Try this:

result = await LoginAPI(value.username, value.password);

Let me know if this was your problem.

Sign up to request clarification or add additional context in comments.

1 Comment

oh nice hint! It works with this way. onPress_login: async function() { var value = this.refs.form.getValue(); if (value) { result = await LoginAPI(value.username, value.password);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.