-2

I am working on project in ReactJS , I am fetching data from server through API . I did some search filtration , I want to display message if there is no records available? I am beginner to ReactJS and don't have much knowledge related to ReactJS . Someone please help me out how to solve this problem ? . Thanks

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

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
Jon
  • 235
  • 1
  • 7
  • 20

2 Answers2

2

You need to account for a few things:

  • Data is loading
  • Data finished loading, results found
  • Data finished loading, no results found
  • API call failed, server error, something else went wrong (this won't be covered in this answer)

Here is a simplified example covering the first three points.

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            data: []
        };
    }
    componentDidMount() {
        // simulating API response
        setTimeout(() => {
            this.setState({
                loading: false,
                data: [{ name: "foo" }, { name: "bar" }]
            });
        }, 2000);
    }
    render() {
        const { loading, data } = this.state;
        return loading === true
        ? <div>Loading...</div>
        : <div>
            {!data.length
                ? <div>No data found.</div>
                : data.map(item => <div>{item.name}</div>)
            } 
        </div>
    }
}

CodeSandbox demo: https://codesandbox.io/s/jzv12lx2v9

wdm
  • 6,659
  • 1
  • 22
  • 27
0

If all you need is to show a message if there are no records found you can literally just check for the data attribute in your state.

{ data.length===0 && <p>No data to show.</p>}

However, you might want to look into checking if the http response is actually valid before setting the state with it.

  • You can make it even shorter: ```{ !data.length &&

    No data to show.

    }```
    – flppv Mar 15 '19 at 01:59
  • @vicodin Actually , I want that If user is searching something if data is not available I want to show message . It working but It just working for pagination – Jon Mar 15 '19 at 14:53