skip to Main Content

In the react component below I want to display the current value of a url query param after updating it. Something like this is straightforward to do with react-router, but I am trying to implement manually in a more minimal app. The code below effectively updates the url, but does not trigger a re-render, so the displayed value never updates.

export default function ExampleComponent() {
    const params = new URLSearchParams(location.search);
    const randomValue = params.get("random");

    function updateRandomValue() {
        const updatedValue = Math.random().toString();
        const newURL = new URL(location.href);
        newURL.searchParams.set("random", updatedValue);
        history.pushState("", "", newURL);
    }

    return (
        <>
            <p>random value is {randomValue || "none"}</p>
            <button onClick={updateRandomValue}>update new random value</button>
        </>
    );
}

Am I handling the navigation wrong? Does there need to be a useEffect involved somehow? Is this functionality impossible without an outer component and/or some use of react state?

2

Answers


  1. Chosen as BEST ANSWER

    Figured it out after a little more noodling. Still need to get a better handle on the why, but changing the click handler from my original snippet to below resolves the bug, without needing additional state:

    function updateRandomValue() {
        const updatedValue = Math.random().toString();
        params.set("random", updatedValue);
        location.search = params.toString();
    }
    

  2. I think you would need to use useEffect with a state dependency. Maybe something like:

    const [urlParam, setUrlParam] = useState("none");
    
    useEffect(() => {
      const params = new URLSearchParams(location.search);
      const randomValue = params.get("random");
      setUrlParam(randomValue);
    }, [urlParam])
    

    and then

    <p>random value is {urlParam}</p>

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search