What is the correct way to use AsyncStorage to upd

2019-02-20 03:42发布

问题:

I'm trying to make a GET request to a server to retrieve a list of products in JSON form. I then want to put the data into AsyncStorage so I can display the products in the view. What's the correct way to do this?

What I've researched:

on https://facebook.github.io/react-native/docs/asyncstorage.html , in the example, they explain how to retrieve a value from AsyncStorage, not set it and retrieve it at the same time

What I have:

componentDidMount () {
    this.fetchProducts()
    this._loadInitialState().done();
}

_loadInitialState = async () => {
    try {
        var value = await AsyncStorage.getItem('products')
        if (value != null) {
            this.setState({products: value});
        }
    } catch (error) {
        console.log("error setting product list");
    }
}

fetchProducts() {
    fetch("http://localhost:3000/products",{
      method: "GET",
      headers: {
        'Content-Type': 'application/json'
      },
    })
    .then((response) => (response.json()))
    .then((data) => setProductList(data)); 

}

setProductList(json_data) {
    Async.setItem('products': json_data);
}

render() {
    console.log(this.state.products) 
    //render view
}

-> this.state.products is null and I know for sure the server returns a response through curl. I'm new to react-native so perhaps my thinking is off. Could someone explain the correct way to do this or suggest an alternative method?

What I know Async storage is a key value store where an app can place its data. This data can be put from async storage into the object's state and the view will update accordingly

回答1:

Instead of setting and getting from async storage, you can just set it to state once you get the data from your fetch request:

componentDidMount () {
    this.fetchProducts()
}

fetchProducts() {
    fetch("http://localhost:3000/products",{
      method: "GET",
      headers: {
        'Content-Type': 'application/json'
      },
    })
    .then((response) => (response.json()))
    .then((data) => setProductList(data)); 

}

setProductList(json_data) {
    this.setState({ products: json_data }, () => {     //Here
      Async.setItem('products': json_data);
    }
}

render() {
    console.log(this.state.products) 
    //render view
}