简体   繁体   中英

React Native - data is not set in state when fetching

I am trying to fetch data from my api and set it in _data state; however, I always get _data state as undefined. First I am pulling a token from asyncstorage before fetching and then I want to save the data from fetching to the state. Can someone please check if I am doing something wrong?

export default class Posts extends React.PureComponent {
  constructor(props) {
    super(props);
    this.fetchData = this._fetchData.bind(this);
    this.state = {
      isLoading: true,
      isLoadingMore: false,
      _data: null,
      accessToken: "",
    };
  }

async componentWillMount() {
try {
      let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN).then(JSON.parse);
      if(!accessToken) {
          this.redirect('login');
      } else {
        this.setState({accessToken: accessToken})
  }
} catch(error) {
    console.log("Something went wrong");
    this.redirect('login');
}  

 this.fetchData(responseJson => {
  const data = responseJson.data;
  this.setState({
    isLoading: false,
    _data: data,
  });
});
}    

  _fetchData(callback) {
    fetch(`https://mywebsite.com/posts`,
         {
         method: 'GET',
         headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json',
           'Authorization': "Bearer " + this.state.accessToken.token,
         }
    })
      .then(response => response.json())
      .then(callback)
      .catch(error => {
        console.error(error);
      });
  }

Where specifically are you losing the "data" value? Are you sure the responseJson has the "data" value in it?

You may be losing scope to this after the bind() call; try this:

   constructor(props) {
    var self = this;
    super(props);
    this.fetchData = this._fetchData.bind(this);
    this.state = {
      isLoading: true,
      isLoadingMore: false,
      _data: null,
    accessToken: "",
  };

    // self.data here should be there if this.data is not.
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM