zbludd
zbludd

Reputation: 37

When returning content from getInitialProps, is there a method to check for empty?

I am quite new to React & NextJS, coming over from the PHP language. This is quite fun and exciting for me - but haven't been able to grasp this part yet.

Can you check for empty in the getInitialProps? For instance, show an error message if the API is down or the API doesn't return any results?

Forgive me for posting my code, but here it is...

import App, { Container } from 'next/app';
import Layout from '../components/Layout'; 
import Footer from '../components/Footer';
import 'isomorphic-fetch'; // Library for fetching data 
import Link from 'next/link';
import {Jumbotron, Button, Row} from 'reactstrap';

export default class Index extends React.Component {
  static async getInitialProps() {

        // Connect to the API
        const ApiResponse = await fetch('http://localhost:1337/mods')

       // Store the data fetched from ApiResponse
       const ModsData = await ApiResponse.json()

        // return mods (first is table name in API, second is the ModsData variable above where we store the json data)
        return {
          mods: ModsData

        }


  }
  render() {
    return <Layout>



     <span style={{borderBottom: '1px solid #ccc', paddingBottom: '5pt', marginTop: '5pt'}}>

     <h4 style={{paddingTop: '10pt'}}>Showing all mods</h4>
     </span>

      <ul className="list-group" style={{paddingTop: '10pt'}}> 
        {this.props.mods.map(Mod => // Get our mods & loop over them
       <li className="list-group-item" key={Mod.id}>
        <Link as={`/mods/${Mod.id}`} prefetch href={`/mods/id=${Mod.id}`}><a>

        {Mod.name}</a></Link>
        {Mod.description}

        </li>

        )}
        </ul>
    </Layout>
  }
}

Upvotes: 0

Views: 750

Answers (2)

Archer11
Archer11

Reputation: 75

try and catch is perfect for this right? if error you can set error as part of your props

Upvotes: 1

Ertan Hasani
Ertan Hasani

Reputation: 1773

Just add another prop noData, and check if the ModsData is returning anything, if not that add noData: true else noData: false

    static async getInitialProps() {
        let noData = false
        // Connect to the API
        const ApiResponse = await fetch('http://localhost:1337/mods').then((value) => {
            if(!value) noData = true;
        }).catch(err => {
            noData = true;
        })

       // Store the data fetched from ApiResponse
       const ModsData = await ApiResponse.json()

        // return mods (first is table name in API, second is the ModsData variable above where we store the json data)
        return {
          mods: ModsData,
          noData
        }
  }

 render(){
      if(this.props.noData) return <h1>No Data</h1>

      //return other code
  }

Upvotes: 1

Related Questions