killer_manatee
killer_manatee

Reputation: 405

React component class, can't write async method?

I'm hazy on async, and I'm not sure why I'm getting a syntax error in my react component while trying to write a simple async method.

class Locations extends React.Component {
  constructor(props) {
    super(props);

    this.searchProducts = this.searchProducts.bind(this);

  }

    async searchProducts(product_name, storeId) {
    let response =  await axios.get(
      `https://api.goodzer.com/products/v0.1/search_in_store/?storeId=${storeId}&query=${product_name}&apiKey=125cbddf3880cb1ba652a7c269ba1eb0`
    );
    console.log(response);
    return response.data.products;

}

  componentWillMount() {
    let products = [];
    this.props.searchLocations(this.props.navigation.state.params.product_name, this.props.navigation.state.params.searchRadius)
      .then(
          products = (this.props.locations.map(
          location => ({[location.id]: this.searchProducts(
            this.props.navigation.state.params.product_name, location.storeid
          )}))
        )
      );

      console.log(products);
  }

  render() {
    const displayLocations = this.props.locations.map(
      location => (<Text key={location.id}>{location.name}</Text>)
    );
    return (
      <View>
        <Text>HELLO</Text>
        <View>{displayLocations}</View>
      </View>
    );
  }
}

I'm getting a syntax error: 'Unexpected token, expected ('.

I don't understand how this is any different than the examples given here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function

Upvotes: 1

Views: 1798

Answers (2)

Deadron
Deadron

Reputation: 5289

Your componentDidMount function is syntactically invalid. You have not supplied a proper function to the then call. Also, your console.log should be inside the then call.

Upvotes: 0

guest271314
guest271314

Reputation: 1

The syntax error is at

  .then(
      products = /* missing `>` at arrow function */ (this.props.locations.map(
      location => ({[location.id]: this.searchProducts(
        this.props.navigation.state.params.product_name, location.storeid
      )}))
    )
  )

.then() expects a function as argument, this.searchProducts() returns a Promise object, async also need to be set within .map() callback function

async componentWillMount() {
  let products = await this.props
  .searchLocations(
    this.props.navigation.state.params.product_name, 
    this.props.navigation.state.params.searchRadius
  )
  .then(
    () => 
        Promise.all(this.props.locations.map(async(location) =>
          ({[location.id]: await this.searchProducts(
            this.props.navigation.state.params.product_name, 
            location.storeid
          )}))
        )
  );
  console.log(products);
}

Upvotes: 2

Related Questions