-
-
Save gnppro/a8d8f68c037aec5e63cc6e8d5d471557 to your computer and use it in GitHub Desktop.
| import Layout from '../components/MyLayout.js' | |
| import Link from 'next/link' | |
| // import fetch from 'isomorphic-unfetch' | |
| import axios from 'axios' | |
| const Index = (props) => ( | |
| <Layout> | |
| <h1>Batman TV Shows</h1> | |
| <ul> | |
| {props.data.map(({show}) => ( | |
| <li key={show.id}> | |
| <Link as={`/p/${show.id}`} href={`/post?id=${show.id}`}> | |
| <a>{show.name}</a> | |
| </Link> | |
| </li> | |
| ))} | |
| </ul> | |
| </Layout> | |
| ) | |
| Index.getInitialProps = | |
| async function() { | |
| // fetch('https://api.tvmaze.com/search/shows?q=batman') | |
| // const data = await res.json() | |
| const res = await axios.get('https://api.tvmaze.com/search/shows?q=batman') | |
| const data = await res.data | |
| console.log(`Show data fetched. Count: ${data.length}`) | |
| return { | |
| data: data | |
| } | |
| } | |
| export default Index |
La principal diferencia entre Server Side Rendering y Client Side Rendering es que con SSR el server envía el HTML con todo el contenido listo para renderizar. Esto es mucho más performante (ya que para nuestro browser es como si fuese un sitio estático) e indexa mejor en buscadores, ya que podemos acceder a todo el contenido fácilmente con curl/wget.
En comparación, con CSR tradicional el server manda un HTML vacío, y tenemos que descargar toda la aplicación y esperar que haga lo suyo para poder empezar a ver el contenido. Esto es mucho más lento y requiere un browser que ejecute JS para funcionar correctamente.
Next.JS usa una mezcla de los dos: SSR para la carga inicial (por ser más rápido), y CSR cada vez que clickeamos en un link con la app inicializada, ya que ahí puede aplicar varias optimizaciones y mecanismos de precarga que hacen que todo funcione lo más rápido posible.
import 'isomorphic-fetch'
import Link from 'next/link'
export default class extends React.Component {
static async getInitialProps() {
let req = await fetch('https://api.audioboom.com/channels/recommended')
let { body: channels } = await req.json()
return { channels }
}
render() {
const { channels } = this.props
// const channels = this.props.channels
return <div>
<header>Podcasts</header>
<div className="channels">
{ channels.map((channel) => (
<a className="channel" key={ channel.id }>
<img src={ channel.urls.logo_image.original } alt=""/>
<h2>{ channel.title }</h2>
</a>
)) }
</div>
<style jsx>{`
header {
color: #fff;
background: #8756ca;
padding: 15px;
text-align: center;
}
.channels {
display: grid;
grid-gap: 15px;
padding: 15px;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
}
a.channel {
display: block;
margin-bottom: 0.5em;
color: #333;
text-decoration: none;
}
.channel img {
border-radius: 3px;
box-shadow: 0px 2px 6px rgba(0,0,0,0.15);
width: 100%;
}
h2 {
padding: 5px;
font-size: 0.9em;
font-weight: 600;
margin: 0;
text-align: center;
}
`}</style>
<style jsx global>{`
body {
margin: 0;
font-family: system-ui;
background: white;
}
`}</style>
</div>
}
}
static async getInitialProps({ query }) {
let idChannel = query.id
or
static async getInitialProps(query) {
let query = data.query
let idChannel = query.id
export default class extends React.Component {
static async getInitialProps({ query }) {
let idItem = query.id
let req = await fetch(`http://localhost:3004/api/v1/items/${idItem}`)
//data
let { body: { channel } } = await req.json()
//return { item: item }
return { channel }
}
render() {
const { channel } = this.props
return (
<h1>{ channel.title }</h1>
)
}
}
Varias Request de url API distintas:
let[req1, req2] = awaitPromise.all([
fetch(url_1),
fetch(url_2)
])
¿Que diferencia hay entre isomorphic-unfetch y axios al usarlo en next.js?
Hello ! Do you have an example with axios interceptors?
The difference between fetch and axios, just axios gives you more functionality when ordering, but the core of the operation is the same (make requests). At least I see it that way
Highlight and format
import Layout from '../components/MyLayout.js'
import Link from 'next/link'
// import fetch from 'isomorphic-unfetch'
import axios from 'axios'
const Index = (props) => (
<Layout>
<h1>Batman TV Shows</h1>
<ul>
{props.data.map(({show}) => (
<li key={show.id}>
<Link as={`/p/${show.id}`} href={`/post?id=${show.id}`}>
<a>{show.name}</a>
</Link>
</li>
))}
</ul>
</Layout>
)
Index.getInitialProps =
async function() {
// fetch('https://api.tvmaze.com/search/shows?q=batman')
// const data = await res.json()
const res = await axios.get('https://api.tvmaze.com/search/shows?q=batman')
const data = await res.data
console.log(`Show data fetched. Count: ${data.length}`)
return {
data: data
}
}
export default IndexOriginal post
export default class extends React.Component {
static async getInitialProps({ query }) {
let idItem = query.id
let req = await fetch(`http://localhost:3004/api/v1/items/${idItem}`)
//data
let { body: { channel } } = await req.json()
//return { item: item }
return { channel }
}
render() {
const { channel } = this.props
return (
<h1>{ channel.title }</h1>
)
}
}let [ res1, res2 ] = await Promise.all([
fetch(url_1),
fetch(url_2)
]);
Ejemplo:
https://github.com/WilliamVelazquez/podcasts.git
https://github.com/Aerolab/platzi-nextjs