Home > Mobile >  Passing a value from one request to another request in ReactJs
Passing a value from one request to another request in ReactJs

Time:06-09

I need help because I couldn't use a separate function to generate the token - it gives out a promise, not a value. I was told that a value can only be used inside a function.

For each request, I generate a new token in the first request and then pass that token into the second request.

I tried making a separate function to generate the token, but fetch returns a promise.

As a result, I made such a big function and it works. Is there a way to make a separate function for the first request and pass the result to the second request?

The first token generation function is required frequently, while the second request is always different.

    fetch('/api/token', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 'id': '5' }),
    })
    .then(response => response.json())
    .then(result => {

    fetch('/api/reviews', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer '   result.token,
      },
      body: JSON.stringify({ 'limit': 10 }),
    })
      .then(response => response.json())
      .then(result => {
          this.setState({ data: result.data });
      })

    })

CodePudding user response:

create a function that return promise

async function getToken() {
   return await fetch('/api/token', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 'id': '5' }),
    })
        .then(response => response.json())
        .then(result => {
            return Promise.resolve(result.token);
        }).catch(error => {
            return Promise.reject(error);
        })
}


async function getReview() {
    const token = await getToken().then(token => {
        return token
    }).catch(error => {
        //handle error
    });
    fetch('/api/reviews', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer '   token,
        },
        body: JSON.stringify({ 'limit': 10 }),
    })
        .then(response => response.json())
        .then(result => {
            this.setState({ data: result.data });
        })

}

i did not test this code but you get the idea

i will test and update my answer asap

CodePudding user response:

Yes you can with async / await. It will allow you to lift the lexical scope of the API response from inside the .then "callback hell" and into the parent function scope.

Your separate function which fetches the token will return a promise, but then the requesting function will wait for the promise to execute and resolve before continuing.

async function fetchToken() {
  const response = await fetch('/api/token', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ 'id': '5' }),
  })
  return await response.json();
}

async function getReviews() {
  const response = await fetch('/api/reviews', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer '   result.token,
    },
    body: JSON.stringify({ 'limit': 10 }),
  })
  const result = await response.json();
  this.setState({ data: result.data });
}

Additionally, if the token call does not need to be made every time the reviews call is made, then you can memoize the value, and use that memoized value.

const tokenMemo = useMemo(async () => await getToken(), []);

async function getReviews() {
  const response = await fetch('/api/reviews', {
  // ...
      'Authorization': 'Bearer '   tokenMemo,
  // ...
}
  • Related