Skip to content

Instantly share code, notes, and snippets.

@pkellner
Created October 30, 2018 18:14
Show Gist options
  • Save pkellner/dfed5693a00b3ea9b63c0be35822dc1f to your computer and use it in GitHub Desktop.
Save pkellner/dfed5693a00b3ea9b63c0be35822dc1f to your computer and use it in GitHub Desktop.
This is a revised version of the data-fetch example index.js file from https://github.com/zeit/next.js/blob/canary/examples/data-fetch/pages/index.js
import React from 'react'
import Link from 'next/link'
import axios from 'axios'
export default class Index extends React.Component {
constructor(props) {
super(props);
console.log("Index:constructor called");
this.state = {
isLoading: props.isLoading,
hasErrored: props.hasErrored,
statusCode: props.status,
statusText: props.statusText,
message: props.message,
stars: props.stars
}
}
static getInitialProps() {
var promise = axios.get('https://api.github.com/repos/zeit/next.js').then(response => {
return {
hasErrored: false,
isLoading: false,
stars: response.data.stargazers_count
};
})
.catch(error => {
return {
hasErrored: true,
isLoading: false,
statusCode: error.response.status,
statusText: error.response.statusText,
message: error.message
}
});
return promise;
}
render() {
const {isLoading, hasErrored, statusCode, statusText, message, stars} = this.state;
if (hasErrored) {
return <p>ErrorCode: {statusCode} ErrorMessage: {statusText} message: {message}</p>
}
if (isLoading) {
return <p>...loading</p>
}
return (
<div>
<p>Next.js has {stars} ⭐️</p>
<Link prefetch href='/preact'><a>How about preact?</a></Link>
<block>
isLoading: {isLoading} hasErrored: {hasErrored}
</block>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment