In my app, I have a togglable switch that is either checked or unchecked based on the dynamic URL of the app. For example, if the URL has a param called followType
set to following
(e.g. https://www.example.com/home?followType=following
), I want the switch to be already checked on page load.
However, the useRouter()
function initially gets the following type as null
and then takes a second to get the actual value for the param. This change is not reflected in what I'm returning and only when I update the state of the page does the switch actually reflect the values in the param.
Here's a code sample below:
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import Switch from "react-switch";
const FollowToggle = () => {
const router = useRouter();
const [checked, setChecked] = useState(router.query.followType === "following" ? true : false)
const handleChange = nextChecked => {
setChecked(nextChecked);
};
return (
<Switch
checked={checked}
onChange={handleChange}
...
TLDR; how do I update the state of the switch that I am returning when the router.query.followType
changes from null
to the actual value in the URL?
You can use useEffect
to listen to router.query.followType
state update in this case.
useEffect
can check every state update from your states automatically.
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import Switch from "react-switch";
const FollowToggle = () => {
const router = useRouter();
const [checked, setChecked] = useState(router.query.followType === "following")
useEffect(() => {
setChecked(router.query.followType === "following")
}, [router.query.followType])
const handleChange = nextChecked => {
setChecked(nextChecked);
};
return (
<Switch
checked={checked}
onChange={handleChange}
...