Next.js Discord

Discord Forum

Conditional rendering after hydration (need to use query parms)

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
I have a state, I want to set this state to a query param on the url. When i use useSearchParams next/navigation , it is un-usable
on the first render on the client. It is through the second render the query parm becomes accessible (doesnt return null)

The problem im having right now is the way im trying to get it to work is basically:

IF NO QUERY PARAMS IN URL, FALLBACK TO DEFAULT
OTHERWISE, USE QUERY PARMS

and UNTIL QUERY PARAMS are potentially available, set to NULL

    let searchParams = useSearchParams()
    let defaultChain = "ETH"

    let [chain, setChain] = useState(searchParams.get('chain') ?? (searchParams ? defaultChain : null))
    useEffect(() => {
        
        setChain(searchParams.get('chain') ?? defaultChain)

    }, [searchParams])

This doesnt work because, if the url was accessed with no searchparams in the url, chain stays "null" when it should fall back to "defaultChain".

0 Replies