React Best Practices

Handling asynchronous code

Always use async/await instead of promise chains

When writing an asynchronous function, resort to the async/await syntax rather than promise chains or callbacks.

Instead of this:

1loadProfile(id) {
2  return API.fetchProfileData(id).then(profile => {
3    this.setState({ profile })
4    this.props.navigate(`settings/profile/${id}`)
5  })
6}

It should be written like this:

1async loadProfile(id) {
2  try {
3    const profile = await API.fetchProfileData(id)
4    this.setState({ profile })
5    this.props.navigate(`settings/profile/${id}`)
6  } catch (err){
7    console.log(err)
8  }
9}

Always use try/catch blocks with Async functions

When writing an async function, wrap everything in a try/catch block.

Instead of this:

1async initializeSQLjs() {
2  const existingCode = localStorage.getItem(this.editorInputKey);
3  const SQL = await sqljs({
4    locateFile: () =>
5      `https://cdn.jsdelivr.net/npm/sql.js@1.3.0/dist/sql-wasm.wasm`,
6  });
7}

It should be written like this:

1async initializeSQLjs() {
2  try {
3    const SQL = await sqljs({
4      locateFile: () =>
5        `https://cdn.jsdelivr.net/npm/sql.js@1.3.0/dist/sql-wasm.wasm`,
6    });
7  }
8  catch (error) {
9    console.log(error);
10  }
11}