0

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?

4
  • 2
    export default async function HomeScreen() { }; not working? Commented Apr 2, 2020 at 8:55
  • @HagaiHarari: I tried that, but this will always result in the error "Objects are not valid as a React child" Commented Apr 2, 2020 at 9:32
  • 1
    export default HomeScreen = async () => {} ? Commented Apr 2, 2020 at 9:37
  • 1
    Same result unfortunately. I got it to work now using Radovix Answer, it seems to be quite elegant without using await at all. Commented Apr 2, 2020 at 9:45

1 Answer 1

1

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);
}
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.