SajjadZare
SajjadZare

Reputation: 2378

Return json data from Function

I use a function for Fetch with below code :

var URL='...'

export function PostData(method,data){
    fetch(URL+method,{
        method:'POST',
        body:JSON.stringify(data),
        headers:{'Content-Type':'application/json'},

    }).then(res => res.json())
    .then(response => {
        var ret=JSON.stringify(response)
        return ret
    })
    .catch((error) => {
        console.error(error)
    })
}

and use it like below :

var retData=PostData('login/Authenticate',data)

retData is empty but in function ret has data

Upvotes: 1

Views: 352

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

It is empty at this point because the call to fetch is asynchronous and the literal is set to undefined as it moves to the next statement because it has not been resolved yet. One way around it is to return the promise object itself and then use .then to get the response once it is resolved.

var URL = '...'

export function PostData(method, data) {
  // return the promise object
  return fetch(URL + method, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json'
      },

    }).then(res => res.json())
    .then(response => {
      var ret = JSON.stringify(response)
      return ret
    })
    .catch((error) => {
      console.error(error)
    })
}

PostData('login/Authenticate',data).then(response => {
   // do something with the response
});

A cleaner approach would be is to use the async/await ES7 feature which makes it more readable.

var URL = '...'

export function PostData(method, data) {
  // return the promise object
  return fetch(URL + method, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json'
      },

    }).then(res => res.json())
    .then(response => {
      var ret = JSON.stringify(response)
      return ret
    })
    .catch((error) => {
      console.error(error)
    })
}

async function getData() {
    let retData = await PostData('login/Authenticate',data);
}

Upvotes: 1

Michiel Dral
Michiel Dral

Reputation: 4074

You PostData function does currently not return anything, so it is empty. First step would be to add a return statement:

export function PostData(method,data){
  return fetch(URL+method,{
    method:'POST',
    ...

This will make your function return a value, but not just a simple value, but a promise! Promises are not the easiest to understand, but there is also a of people who tried to explain them
- https://developers.google.com/web/fundamentals/primers/promises
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Now how can you use the value anyway?

PostData('login/Authenticate',data)
.then(retData => {
  // ... use retData here
});

Now, you used the react-native tag, so I am assuming you want to use this value in your render function. You can't do this simply by putting the PostData call in your render function. You'll have to put it in state, and then use that value in render:

state = { retData: null }

componentDidMount() {
  PostData('login/Authenticate',data)
  .then(retData => {
    // This puts the data in the state after the request is done
    this.setState({ retData: retData });
  });
}

render() {
  let retData = this.state.retData;
  // ... use retData in your render here, will be `null` by default

There are a lot more different or cleaner ways to do this, but I tried to keep this answer as simple and bare as possible :)

Upvotes: 1

Related Questions