0

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.

1 Answer 1

1

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>
    </>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.