What is the correct way to use AsyncStorage to update state in React-Native?

邮差的信 提交于 2019-11-30 20:08:26

问题


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
}


来源:https://stackoverflow.com/questions/41495412/what-is-the-correct-way-to-use-asyncstorage-to-update-state-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!