eoinzy
eoinzy

Reputation: 2242

React Native returning function from getter

I am making an app which stores some local data, such as an auth token. When the app gets closed, this data gets cleared so I want to move it into AsyncStorage.

It looked like this before:

let LocalData = {
  token: '',
  name: '',
  otherStuff: '',
  moreStuff: '',
};

export default LocalData;

And I accessed it like LocalData.name = 'John';

So basically I have refactored the code so that my local data class is a wrapper for AsyncStorage.

See here:

    class LocalData {
      
      setObjectForKey = async (key, value) => {
        if (!key) throw new Error('Cannot set an value (' + value + ') without a key');
    
        return await AsyncStorage.setItem(key, value)
      };
      
      setToken(token) {
        this.setObjectForKey(KEY_TOKEN, token)
      }
      
      token = async () => {
          try {
            let item = await AsyncStorage.getItem(KEY_TOKEN);
    
            if (item === null) { return 'N/A'; }
    
            return item;
          } catch (error) {
            console.log('Error fetching token', error);
          }
      }
    }

export default LocalData;

There are about 10 items I want to store this way. This is an example of one of them.

I then call it like this:

var localData = new LocalData();
doSomething(localData.token);

or if I set the value, I do it like this:

var localData = new LocalData();
localData.setToken(someToken);

This is my first React Native app so I think my issue is that I just don't know the correct syntax.

Can someone point me in the direction of where I'm going wrong here?

My goal is to have a basic class with getters and setters.

Thanks.

Upvotes: 0

Views: 388

Answers (1)

Lee Brindley
Lee Brindley

Reputation: 6502

Looks like this is your issue:

var localData = new LocalData();
doSomething(localData.token); // << This line

I assume you're trying to pass the value of the token into the 'doSomething' function. The code above isn't doing that, it's passing in a reference to the token function.

Given in your class it's an async method, it returns a promise, so to access the token you'd either need to use async/await or the Promise API:

async/await

async function foo () {
    
    let localData = new LocalData();
       
    try {
       // Use await to await the promise resolving with the token
       let token = await localData.token();
    } catch (e) {
        console.log("Error", e);
    }
}

Promise api

function foo () {
    
    let localData = new LocalData();
    
    localData.token()
        .then(doSomething)
        .catch(function (e) {
            console.log("Error", e);
        });
}

Summary

You're getting a function because you're not calling the function, you're using the reference to the function as a value, rather than calling the function to get the returned value.

Upvotes: 1

Related Questions