Search code examples
reactjsapiaxiosconditional-rendering

conditional rendering at empty response of API in react js


I am building a little react js application where users can select a few filters and get response accordingly. For some values selected by users, nothing is found from database and I want to show "nothing found" message.

I tried using if & else conditional operators which is not producing results. Below is the code.

        .then(res => {
            if(!res.data.length){
                return(
                    <div>
                        <h1>nothing found.</h1>
                    </div>
                )
            }
            else{
            this.setState({ data: res.data,urlList:[] }) 
            console.log(this.state)  
            }                                                                    
        })

Now If I do this

        .then(res => {
            if(!res.data.length){
                console.log('nothing found')

            }
            else{
            this.setState({ data: res.data,urlList:[] }) 
            console.log(this.state)  
            }                                                                    
        })

I am getting a response on console. What I am doing wrong ?


Solution

  • declare a new state variable like

     constructor(props){
          super(props);
          this.state = {
              noData: ''
          }
     }
    

    And here

       .then(res => {
            if(!res.data.length){
                this.setState({noData: 'nothing found'});
                console.log('nothing found')
    
            }
            else{
            this.setState({ data: res.data,urlList:[], noData: '' }) 
            console.log(this.state)  
            }                                                                    
        })
    

    And in render just display this.state.noData

    render(){
        return(
              <div>
                   <h1>{this.state.noData}</h1>
              </div>
        )
    }