Part 2: Next.js Fetching data

Pozterz
Pozterz
Aug 24, 2017 · 2 min read

ความเดิมตอนที่แล้ว https://medium.com/@pozterz.jojo/part-1-next-js-%E0%B8%84%E0%B8%A3%E0%B8%B1%E0%B9%89%E0%B8%87%E0%B9%81%E0%B8%A3%E0%B8%81-194929ade49d

เริ่ม !!!

$ yarn add isomorphic-unfetch

pages/index.js

ปรับกันหน่อย จะ fetch ข้อมูล มันจะถูกทำให้เป็น props เนอะ แล้วก็ map ออกมาทีละอัน แปะเป็นลิ้งไป

import Layout from '../components/Layout'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch
const Index = (props) => (
<Layout>
<h1>Batman TV Shows</h1>
<ul>
{props.shows.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() {
const res = await fetch('https://api.tvmaze.com/search/shows?q=batman')
const data = await res.json()
console.log(`Show data fetched. Count: ${data.length}')
return {
shows: data
}
}
export default Index

ผ่างงงงง !!!!

but ..

console ใน client ไงไปปริ้นอยู่บน server ด้วยฟร้ะ

ความจริงแล้วเพราะ client เรามี data อยู่แล้ว จึงไม่จำเป็นที่จะต้อง fetch ข้อมูลใหม่อีกเราจะเห็น console แค่ครั้งแรกที่มัน fetch ข้อมูลเท่านั้น แต่เรา render page ที่ server จึงขึ้น console นี้แล ~~

ต่อๆ

server.js

แก้นิดนึงจาก title เป็น id


const queryParams = { id: req.params.id }

pages/post.js

เหมือนกับหน้า index fetch มา ละตัด tag p ใน summary ออก โชว์รูป ข้อมูลที่ fetch

import Layout from '../components/Layout'
import fetch from 'isomorphic-unfetch'
const Post = (props) => (
<Layout>
<h1>{props.show.name}</h1>
<p>{props.show.summary.replace(/<[/]?p>/g,'')}</p>
<img src={props.show.image.medium} />
</Layout>
)
Post.getInitialProps = async function (context) {
const { id } = context.query
const res = await fetch(`https://api.tvmaze.com/shows/${id}`)
const show = await res.json()

console.log(`Getched show: ${show.name}`)
return { show }
}
export default Post

เท่ไปโลยย

view source ดู

เห็นมั้ยว่ามันมี data ที่เรา fetch แปะอยู่ด้วย ซึ่งมีผลต่อการทำ SEO ไงไงไง ~~

จบ fetch 555

เดี๋ยวมาต่อ part 3 นาจาาาาาาาาาาา :D

)

Pozterz

Written by

Pozterz

Lv.25 Full Stack Pokemon @Pi R Square

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade