vue.jslocalforage

Hot can I use the return of localforage


In my Vue SPA, I use localforage to store the Bearer token.

In a component, i need the token to upload files to the api.

I tried to get the localforage token:

            let token = localforage.getItem('authtoken')
            console.log(token)

It works but the result is a promise object:

Promise

result: "eyJ0eXAiOiJKV1QiyuIiwiaWF0IjoxNTg4MTUzMTkzLCJleHAiOjE1ODg…"

status: "resolved"

When i try to console.log(token.result) it returns null

How can i access the token?


Solution

  • The official documentation states three different approaches to reading values from the storage.

    localforage.getItem('authtoken').then(function(value) {
        // This code runs once the value has been loaded
        // from the offline store.
        console.log(value);
    }).catch(function(err) {
        // This code runs if there were any errors
        console.log(err);
    });
    
    // Callback version:
    localforage.getItem('authtoken', function(err, value) {
        // Run this code once the value has been
        // loaded from the offline store.
        console.log(value);
    });
    
    // async/await
    try {
        const value = await localforage.getItem('authtoken');
        // This code runs once the value has been loaded
        // from the offline store.
        console.log(value);
    } catch (err) {
        // This code runs if there were any errors.
        console.log(err);
    }