chimpRebel83
chimpRebel83

Reputation: 13

Refactoring using Async and await in React?

Im (very) new to react having come from a Java background. I am trying to refactor some existing code to use Async and await.

The error is coming right before my render function() (highlighted with *****) and am getting a "/src/App.js: Unexpected token, expected "," error and cant for the life of me figure out what is going on. Ive tried messing around with } ) and ; and cant quite track it down. Any help is appreciated.

import React, { Component } from "react";
import { FixedSizeGrid } from "react-window";

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      specialties: [],
      isLoaded: false,
      error: null
    };
  }

  async componentDidMount() {
    const response = await fetch (url)
    .then(response => response.json())
    .then(body => {
      const specialties = body.data.specialties;
      return specialties;
    })
    .then(specialties => {
      return specialties.map(({ _id, name }) => {
        return [_id, name];
      })


      .then(transformed => {
        this.setState({
          specialties: transformed,
          isLoaded: true,
          error: null
        });
      })

      .catch(error => {
        this.setState({
          specialties: [],
          isLoaded: true,
          error: error
         });
      });
    }




  render() {***********************here 
    if (this.state.error) {
      return <span style={{ color: "red" }}>{this.state.error.message}</span>;
    }

    if (!this.state.isLoaded) {
      return "Loading...";
    }

    const ITEM_HEIGHT = 35;

    return (
      <FixedSizeGrid
        columnWidth={300}
        rowHeight={35}
        itemData={this.state.specialties}
        height={ITEM_HEIGHT * this.state.specialties.length}
        width={600}
        itemSize={() => ITEM_HEIGHT}
        columnCount={2}
        rowCount={this.state.specialties.length}
      >
        {SpecialtyYielder}
      </FixedSizeGrid>
    );
  }
}

const SpecialtyYielder = ({ columnIndex, rowIndex, data, style }) => {
  return (
    <div
      style={{
        ...style,
        backgroundColor:
          (rowIndex + columnIndex) % 2 ? "beige" : "antiquewhite",
        display: "flex",
        alignItems: "center",
        justifyContent: "center"
      }}
    >
      {data[rowIndex][columnIndex]}
    </div>
  );
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 1

Views: 181

Answers (3)

user120242
user120242

Reputation: 15268

You're missing a bracket and paren:

  async componentDidMount() {
    const response = await fetch (url)
    .then(response => response.json())
    .then(body => {
      const specialties = body.data.specialties;
      return specialties;
    })
    .then(specialties => {
      return specialties.map(({ _id, name }) => {
        return [_id, name];
      })
    })  // missing closing bracket and paren


      .then(transformed => {
        this.setState({
          specialties: transformed,
          isLoaded: true,
          error: null
        });
      })

      .catch(error => {
        this.setState({
          specialties: [],
          isLoaded: true,
          error: error
         });
      });
    }

Async/Await
Basically everywhere you used then, you can just use await instead, but in a way such that you don't need a bunch of callbacks and the logic is like synchronous code:

  async componentDidMount() {
    try {
      const response = await fetch (url)
      const body = await response.json()
      const specialties = body.data.specialties;
      const transformed = specialties.map(({ _id, name }) => {
        return [_id, name]
      })
      this.setState({
          specialties: transformed,
          isLoaded: true,
          error: null
      })
    }
    catch(error) {
        this.setState({
          specialties: [],
          isLoaded: true,
          error: error
        })
    }
  }

Upvotes: 1

ROOT
ROOT

Reputation: 11622

You are missing }) in componentDidMount method:

import React, { Component } from "react";
import { FixedSizeGrid } from "react-window";

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      specialties: [],
      isLoaded: false,
      error: null
    };
  }

  async componentDidMount() {
    const response = await fetch (url)
    .then(response => response.json())
    .then(body => {
      const specialties = body.data.specialties;
      return specialties;
    })
    .then(specialties => {
      return specialties.map(({ _id, name }) => {
        return [_id, name];
      })


      .then(transformed => {
        this.setState({
          specialties: transformed,
          isLoaded: true,
          error: null
        });
      })

      .catch(error => {
        this.setState({
          specialties: [],
          isLoaded: true,
          error: error
         });
      });
    })}



  render() {




    const ITEM_HEIGHT = 35;

    return (
      <FixedSizeGrid
        columnWidth={300}
        rowHeight={35}
        itemData={this.state.specialties}
        height={ITEM_HEIGHT * this.state.specialties.length}
        width={600}
        itemSize={() => ITEM_HEIGHT}
        columnCount={2}
        rowCount={this.state.specialties.length}
      >
        {SpecialtyYielder}
      </FixedSizeGrid>
    );
  }
}

const SpecialtyYielder = ({ columnIndex, rowIndex, data, style }) => {
  return (
    <div
      style={{
        ...style,
        backgroundColor:
          (rowIndex + columnIndex) % 2 ? "beige" : "antiquewhite",
        display: "flex",
        alignItems: "center",
        justifyContent: "center"
      }}
    >
      {data[rowIndex][columnIndex]}
    </div>
  );
};

Upvotes: 0

Andrew
Andrew

Reputation: 7545

Looks like you might need a better text editor ;). It's in your componentDidMount. At the very end you're missing a ), to close off your .then block and then another curly brace to close componentDidMount

  async componentDidMount() {
    const response = await fetch (url)
    .then(response => response.json())
    .then(body => {
      const specialties = body.data.specialties;
      return specialties;
    })
    .then(specialties => {
      return specialties.map(({ _id, name }) => {
        return [_id, name];
      })


      .then(transformed => {
        this.setState({
          specialties: transformed,
          isLoaded: true,
          error: null
        });
      })

      .catch(error => {
        this.setState({
          specialties: [],
          isLoaded: true,
          error: error
         });
      });
    })
}

This addresses your syntax error. The way you phrased the question made it seem like you thought the "resolution" to it was to use async/await. You obviously can still do a refactor. Are you interested in still exploring async/await?

Upvotes: 1

Related Questions