jasonmerino / react-native-simple-store

A minimalistic wrapper around React Native's AsyncStorage.

Home Page:https://www.npmjs.com/package/react-native-simple-store

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

this.props becomes undefined

luisserota opened this issue · comments

Hi!

First of all, great library! It's fantastic and I'm making some pretty heavy use of it.

One issue I thought I'd report. Unless I'm completely mistaken, after calling store.get('X'), the props property of this, this.props, becomes undefined. For the life of me I can't figure out why.

My current implementation looks something like this

class MyComponent extends Component {
 componentDidMount() {

     store.get('some_data')
     .then(function(data){
        console.log(this.props) // this here is undefined
     })
 }
}

Perhaps this has something to do with this while inside the then call then references the store class rather than the component's. Not sure if this is the desired implementation of that or not, but just thought I'd bring it up.

My solution to address this was to assign this.props to a variable before calling methods from the store, and in .then calls for store methods I reference that variable to get what I need from this.props, etc.

Thanks again for the awesome lib!

Hey @luisserota ,

Glad you are enjoying using it. Regarding your loss of context it looks like you are not using an arrow function in your example .then function. Since that is the case you are losing the parent context. If you change it to use an arrow function like this it should fix that issue.

class MyComponent extends Component {
  componentDidMount() {
    store.get('some_data')
    .then((data) => {
      console.log(this.props) // this.props should now be the same as what it was before you called store.get()
    });
  }
}

On another note, if you use async/await you could get around this altogether because you could execute the next step in the function within the same function, rather than having a wrapper function for the .then.

class MyComponent extends Component {
  async componentDidMount() {
    try {
      const data = await store.get('some_data');
      console.log(this.props) // this.props will be the component props.
    } catch (error) {
      // let user know that something went wrong
      // or handle gracefully with a programatic fallback flow through the code
    }
  }
}

Hey Jason,

Thanks for the really thorough response! You're absolutely right, nothing at all wrong with your lib, moreso my obliviousness to the implementation of context in JS/React.

Thanks again!

@luisserota No worries man. :) Context can get a little tricky in JS, especially in callback functions and classes.

Glad you were able to get that all resolved.