Basti
Basti

Reputation: 517

React Native fetch and render json

So I just started to work with React Native and I would like to fetch some json and render some components afterwards. So I created a function loadDocument() which returns the json and a function assembleDocument() which looks like this:

function assembleDocument() {
  return new Promise((resolve) => {
    loadDocument().then((doc) => {
      const first_row = doc.paragraphs[0].rows[0].blocks
      let container

      for (let block = 0; block < first_row.length; ++block) {
        container += <HanziBlock hanzi={first_row[block].hanzi} pinyin={first_row[block].pinyin} />
      }

      resolve(container)
    });
  });
}

Everything seems to work perfectly fine and the function returns an object containing my "HanziBlock" Components. Now I only need to render it:

export default function HomeScreen() {
  let content = await assembleDocument()
  return content;
}

But here's the problem: I cannot use await outside an async function. But if I cannot wait for my content to arrive how can I render it?

Upvotes: 0

Views: 44

Answers (1)

radovix
radovix

Reputation: 3177

You should separate document loading and it's assembling. Maybe something like this will work for you.

constructor() {
  this.state = { doc: null };
}

componentDidMount() {
  loadDocument().then((doc) => this.setState({ doc }));
}

render() {
  if (this.state.doc === null) {
    return 'Loading';
  }

  return assembleDocument(this.state.doc);
}

Upvotes: 1

Related Questions