简体   繁体   中英

How would I return an error message upon a failed search in react.js

I'm currently learning how to code the front end of a webpage in react.js and in order to complete the assignment, I need to return a message saying Campground not found when a user enters anything into the search bar that's not in my database .

For example:

If they type Banana instead of a real campground name , it needs to display the message. I'm sure it's relatively simple I'm just at a complete loss at this point.

Below is the code for my find.js file:

import Layout from '../components/MyLayout.js';
import React from "react";
import {getInfo} from '../lib/utils.js';

class Find extends React.Component {
  constructor(props) {
    super(props);
    this.state={search: ""};
  }

  handleUpdate(evt){
    this.setState({search: evt.target.value});
  }

  async handleSearch(evt){
    const park = await getInfo(this.state.search);
    this.setState({park});
  }

render() {
  return (
    <Layout>
    <div style={{ margin: "auto auto", width: "600px", textAlign: "center" }}>
        <h1>New Mexico Camground Search</h1>
        <p><input type='text' value={this.state.search} onChange={this.handleUpdate.bind(this)}/></p>
        <div className="button-style" onClick={this.handleSearch.bind(this)}>Submit</div>
        {this.state.park ? <div>
        <br />
        <h3>{this.state.park.name}</h3> 
            <br /><img style={{maxWidth: '400px', maxHeight: "400px"}}
            src={this.state.park.image_url} /> <br />
            <h3>{this.state.park.closest_town}</h3>
            <p>{this.state.park.description} </p>
          </div> : null}
      <style jsx>{`
        h1,
        a {
          font-family: 'Sans';
          color: #ffa500;
        }
        h2,
        a {
            font-family: 'Sans'
            color: #ffa500;
        }
        .button-style {
            margin: auto auto;
            cursor: pointer;
            background-color: #ffa500;
            color: #ffffff;
            width: 100px;
            font-family: "Sans";
        }
        ul {
          padding: 10;
        }
        li {
          list-style: none;
          margin: 5px 0;
        }
        a {
          text-decoration: none;
          color: blue;
        }
        a:hover {
          opacity: 0.6;
        }
      `}</style>
      </div>
    </Layout>
      )
  }
    }
}

export default Find;

You can do it with try/catch

async handleSearch(evt) {
  try { 
    const park = await getInfo(evt.target.value);
    this.setState({park});
  } catch(error) {
    // do something with error
  }
}

(You can also use the target value directly)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM