0

I have a class that accesses an API and returns the value in the API:

import React from 'react';

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

        this.state = { customer: [] };
    }

    componentDidMount() {

        fetch('https://surpriserecommenderapi.herokuapp.com/[email protected]', {
            method: "post",
            headers: {
                "Content-Type": "application/json"
            }
        }).then(response => {
            // *** Check for HTTP success
            if (!response.ok) {
                throw new Error(`HTTP error ${response.status}`);
            }
            // *** Read the body, parse it as JSON
            return response.json();
        })
        .then(({ prediction }) => this.setState({ customer: prediction }))
        .catch(error => {
            // ...*** handle/report error...
        });
    }

    render() {

        const customers = this.state.customer.map((item, i) => (
            <div>
                <h1>{item}</h1>
            </div>
        ));

        return (
            <div id="layout-content" className="layout-content-wrapper">
                <div className="panel-list">{customers}</div>
            </div>
        );
    }
}

export default UserList;

{customers} returns a string "Rome" to display on the website. I am trying to call this in App.js. I am able to call UserList and display "Rome" however, I want to create an if statement that checks what the value of what is displayed. Like this:

const recommended = <UserList></UserList>
console.log(recommended);

  const recommendedPackage = () => {
    if(recommended === "Roam in Rome"){
      return(
        <div>Recommended package: Roam in Rome</div>
      )
    } else {
      return(
        <div>No recommended package</div>
      )
    }
  }

Any help would be appreciated!

1
  • Am I getting this right, you are trying to compare a component with a string? <UserList></UserList> is a call to React.createElement(), which is a function, not a string. Commented Apr 6, 2021 at 11:31

1 Answer 1

1

I believe you should implement the required logic in the UserList class, with some sort of conditional rendering. Maybe something like:

class UserList extends React.Component {
  ...
  parseCustomers() {
    return (
      this.state.customers.map(item => {
        if (item === "Rome") {
          // logic here
        } else {
          // logic here
        }
      });
    );
  }

  render() {
    const customers = this.parseCustomers();
    return (
      ...
    );
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this makes a lot of sense!

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.