On my page, there are default query parameters set as '?status=default'
I'm attempting to retrieve the status value dynamically change it using a button trigger
Initially, when the page loads for the first time, it correctly displays the value as 'default'
https://i.sstatic.net/5Y5Pf.png
However, when I try to change the status using an onClick button, the URL behaves as expected, but the value does not update
https://i.sstatic.net/ViVok.png
Below is the code snippet:
import React, { useEffect } from 'react'
import { GetServerSidePropsContext } from 'next'
import { useRouter } from 'next/router'
const TestURL = (props: any) => {
const router = useRouter()
const { query } = router
function handleChangeQueryParams(status: string) {
router.replace(router.asPath, { query: { status } })
}
console.count('rerender')
console.log(query.status)
return (
<div className="flex flex-col gap-4">
Index
<button>{query.status}</button>
<button
onClick={() => handleChangeQueryParams('Test1')}
className="border&qout;
>
change query params
</button>
<button
onClick={() => handleChangeQueryParams('Test2')}
className="border&qout;
>
change query params2
</button>
</div>
)
}
I've tried using useEffect and useState, but it doesn't seem to be working correctly. What am I missing here?
const [status, setStatus] = useState(query.status)
useEffect(() => {
setStatus(query.status)
}, [query.status])