'getServerSideProps always return null object as props
when I tried below code I get null object or undefined in console.
import React from 'react'
function Main({ data }) {
console.log(data);
return (
<div></div>
)
}
export async function getServerSideProps() {
const res = await fetch(`https://api.unsplash.com/search/photos?query=super&client_id=QqHDWLqMPbUQMFYXaMOjLF9iT81ceZzfXkMkiJF1hTQ`)
const data = await res.json()
return { props: { data } }
}
export default Main
Is there any error? I also tried return something in Main function but still get undefined.
Solution 1:[1]
Following the docs
getServerSidePropscan only be exported from a page. You can’t export it from non-page files.
You can't use getServerSideProps in a component. So make your Main.js to be a pages
// pages/main.js
function Main({ data }) {
return <div>Main</div>
}
export async function getServerSideProps() {
const res = await fetch(`https://api.unsplash.com/search/photos?query=super&client_id=QqHDWLqMPbUQMFYXaMOjLF9iT81ceZzfXkMkiJF1hTQ`)
const data = await res.json()
return { props: { data } }
}
export default Main
You should use
getServerSidePropsonly if you need to pre-render a page whose data must be fetched at request time
Or keep Main.js as a component and fetch data on client using useEffect
function Main({ data }) {
const [data, setData] = useState(null)
const [isLoading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
fetch('https://api.unsplash.com/search/photos?query=super&client_id=QqHDWLqMPbUQMFYXaMOjLF9iT81ceZzfXkMkiJF1hTQ')
.then((res) => res.json())
.then((data) => {
setData(data)
setLoading(false)
})
}, [])
if (isLoading) return <p>Loading...</p>
if (!data) return <p>No profile data</p>
return (
<div>// rest of you code</div>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nos nart |
