javascriptreact-nativestatejsxitunes-store

Use AsyncStorage values kept in state and display it


I'm making my first app, "mark what album you've listened" kind of app. I used iTunes search API and for every album listened, I create a key with AsyncStorage using the ID and for the value, the url to the artwork.

So here is the question: I'm stuck at the last step of the app. I want to display all the artwork of all the albums I've listened. For that, I would like to make a foreach loop that for every element in listened, it would take its URL (now that it only contains URLs), put it in an Image tag, return it and display it... But, can I do that?

For that, I created a state called listened. It takes all the AsyncStorage thanks to this function:

  importData = async () => {
    try {
      const keys = await AsyncStorage.getAllKeys();
      const result = await AsyncStorage.multiGet(keys);
      
      console.log(result)
      //listened takes all asyncstorage data
      this.setState({listened: result.map(req => JSON.stringify(req[1]))});
    } catch (error) {
      console.error(error)
    }
  }

Then I made a renderArtwork() function that returns the state when I arrive to the Navigation. For now, it just displays all the URLs:

  renderArtwork(){
    this.importData();
    return(
      <Text>{this.state.listened}</Text>
    )
  }

And the "main":


  render() {
    return(
      <View style={styles.main_container}>
        {this.renderArtwork()}
      </View>
    )
  }

Thank you for your help


Solution

  • It better to move the importData() to your componentDidMount which will call and get the data from asyncstorage when the screen is mounted.

    As for displaying the images, Lets say that your current array 'listened' has the below format

      listened = ['url1','url2'];
    
      renderArtwork() {
        this.importData();
        return this.state.listened.map((url) => (
          <Image
            style={{
              width: 50,
              height: 50,
            }}
            source={{
              uri: url,
            }}
          />
        ));
      }
    

    You can simply map and show all the images in your array, Also the JSON.stringify part wont be necessary as its already a string.