Reputation: 37
I am using useRouter to get some data from user in the query. I can see the query data in the form of HTML. But when I pass that search
inside getServerSideProps
it returns undefined.
function SearchData() {
const router = useRouter()
const { search } = router.query
return (
<div>
<h1>{search}</h1>
</div>
)
}
export async function getServerSideProps({search}) {
console.log(search)
}
Upvotes: 0
Views: 714
Reputation: 4332
The getServerSideProps
function takes in a context
as a parameter and the context
has a query
object which gives you access to your query string.
So instead of destructuring search
consider destructuring query
and using it like this
export async function getServerSideProps({ query }) {
console.log(query.search)
}
Upvotes: 1
Reputation: 13588
You are not suppose to pass search in getServerSideProps.
When you visit http://localhost/page?search=abc, you can retrieve abc from query.search
export async function getServerSideProps({query}) {
console.log('req.query', query)
//do something with the parameter. in this instance - query.search
return {
props: {}, // will be passed to the page component as props
}
}
If you are not using serverSideProps and you want to get the search query string, you need to use useEffect, and wait for router to be ready.
Example
const [ query, setQuery ] = useState()
const router = useRouter()
useEffect(() => {
if (router.isReady) {
setQuery(router.query)
//query.search will then contain the search param
}
}, [router])
Upvotes: 2