1

I am new with React and cannot write correct code for the situation. Let me explain in the code

class Test extends React.Component {
  render() {
    // IndexedDB indexes
    const ids = ['id1', 'id2', 'id3'];

    // fetch data and build a list
    const files = ids.map((id) => 
      localforage.getItem(id).then((entry) => 
        <li key={entry.id}><img src={entry.data} /></li>
      );
    );

    return (
      <ul>{files}</ul>
    )
  }
}

What is the correct way to asynchronous load all data and display it?

1 Answer 1

5

You could do the asynchronous logic in the componentDidMount hook and use setState to put the entries in your state.

Example

class Test extends React.Component {
  state = { entries: [] };

  componentDidMount() {
    const ids = ["id1", "id2", "id3"];

    Promise.all(ids.map(id => localforage.getItem(id))).then(entries => {
      this.setState({ entries });
    });
  }

  render() {   
    return (
      <ul>
        {this.state.entries.map(entry => (
          <li key={entry.id}>
            <img src={entry.data} />
          </li>
        ))}
      </ul>
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.