Niklas Lindeke
Niklas Lindeke

Reputation: 380

Sending results from fetch to another part of program

I am creating an app in React Native and have bumped in to some major issues with fetching data from my server and using it in my program.

My architechture differs a bit from the example provided by React Native in their documentation, but I have tried a bunch of different ways. The token is correct and I am obviously calling the method in a sense correctly, but it does not return the data to the other side of my program.

In Methods.js

exports.loginUser = function(TOKEN) {
      fetch(baseUrl + 'login' , {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        accessToken: TOKEN,
      },)
    })
    .then((response) => response.text())
    .then((responseText) => {

        console.log(typeof responseText);
        return responseText
    })
    .catch((error) => {
      console.warn(error);
    });
  };

Where it logs the type of the data as a string, and it prints out correctly when I call it as is. However, my app can't retrieve the data in any kind of manner, it just returns as undefined.

In Home.js

var Method = require('../Services/Methods');
.
.
.
var ComponentTwo = React.createClass({

  getInitialState: function() {
    return {
      text: 'Loading...',      
    }
  },
  componentDidMount: function() {
    {
      this.setState({
        text: Method.loginUser(AccessToken)
      })
    }
  },

  render: function() {

    console.log(Method.loginUser(AccessToken));
    console.log(this.state.text);

I am in trial and error mode right now, but both of the logs returns undefined, except for my log in Methods.js, so I think there is an issue with just hitting return responseText, but I don't know any other way since they are in two separate files. So I think the issue is within Method.JS since calling it fails in every way I've tried.

Upvotes: 0

Views: 53

Answers (1)

David
David

Reputation: 2821

I think you have to return a promise from your loginUser function, something like:

exports.loginUser = function(TOKEN) {
  return new Promise((resolve, reject) => {
      fetch(baseUrl + 'login' , {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        accessToken: TOKEN,
      },)
    })
    .then((response) => response.text())
    .then((responseText) => {
        console.log(typeof responseText);
        resolve(responseText);
    })
    .catch((error) => {
        reject(error);
    });
  });
};

And then call your function like this:

Method.loginUser(AccessToken)
.then((res) => console.log(res))
.catch((error) => console.log(error))
.done();

I have not verified that the above code is working, it's just to give you an idea.

Upvotes: 1

Related Questions