Home > other >  How can I use query string in next js?
How can I use query string in next js?

Time:07-06

If i go to my site www.example.com/page?my-string, I check for the string but can't do anything with it.

import { useRouter } from "next/router";

export default function Index() {

  const router = useRouter();

  let str = null;

  "my-string" in router.query ? (str = true) : (str = false);

  const [myState, setMyState] = useState(str);

  console.log(str) /* this logs false twice and then true once */
  console.log(myState) /* this logs false three times */

  return (
    <>
      <GlobalState.Provider value={[myState, setMyState]}>
         <Page />
      </GlobalState.Provider>
    </>
  );
}

I'm trying to pass this state in GlobalState, it always passes false. I played around with useEffect, but I can't figure it out.

CodePudding user response:

useState only assigns the default value once in the first rendering. In subsequent renderings, you need to listen to route.query change with useEffect for state update.

import { useRouter } from "next/router";

export default function Index() {

  const router = useRouter();
  const [myState, setMyState] = useState("my-string" in router.query);

  useEffect(() => {
     setMyState("my-string" in router.query);
  }, [router.query]);

  return (
    <>
      <GlobalState.Provider value={[myState, setMyState]}>
         <Page />
      </GlobalState.Provider>
    </>
  );
}
  • Related