0

I am new to Fetch Javascript.

I use fetch to get data from API and I want to use specific data from the response and use it to another place outside fetch.

fetch("https://backend.org/api/v2/auth/login", requestOptions)
    .then(response => response.text())
    //~ .then(result => console.log(result))
    .then(result => {
        console.log(result);
        let  loginResult = JSON.parse(result);
        var keyForOTP = loginResult.result.key;

    })
    .catch(error => console.log('error', error));   

I want to use keyForOTP to another function as variable.

How i can achieve that. because I call variable keyForOTP outside fetch it turns undefined

tom10271
  • 4,222
  • 5
  • 33
  • 62

1 Answers1

0

Use Promise

function fetchOTPKey() {
    return new Promise((resolve, reject) => {
        fetch("https://backend.org/api/v2/auth/login", requestOptions)
            .then(response => response.text())
            .then(result => {
                console.log(result);
                let loginResult = JSON.parse(result);
                var keyForOTP = loginResult.result.key;

                resolve(keyForOTP);
            })
            .catch(error => {
                console.log('error', error);

                reject(error);
            });
    })
}

fetchOTPKey().then(
    (keyForOTP) => {
        console.log(keyForOTP);
    }
)

Use async

async function fetchOTPKey() {
    try {
        const response = await fetch("https://backend.org/api/v2/auth/login", requestOptions)

        const result = response.text();
        console.log(result);
        let loginResult = JSON.parse(result);
        var keyForOTP = loginResult.result.key;

        return keyForOTP;
    } catch (e) {
        console.log('error', e);
    }
}

const keyForOTP = await fetchOTPKey();
tom10271
  • 4,222
  • 5
  • 33
  • 62