8

I would like to know how to set or unset a parameter in the router.query.

In the example I have 2 check boxes, when I toggle a I want the query value a to toggle and when I toggle b I want the query value b to toggle.

This is the example code:

import { useState, useEffect } from "react";
import { withRouter } from "next/router";
import Layout from "../components/Layout";
const Test = ({ router }) => {
  const [query, setQuery] = useState(router.query);
  const changeQuery = val => e =>
    setQuery({ ...query, [val]: e.target.checked });
  const { a, b } = query;
  useEffect(() => {
    //what do I do here to set query param?
  }, [a, b]);
  return (
    <Layout>
      <pre>{JSON.stringify(router.query, undefined, 2)}</pre>
      a:
      <input
        type="checkbox"
        value="a"
        checked={a}
        onChange={changeQuery("a")}
      />
      b:
      <input
        type="checkbox"
        value="b"
        checked={b}
        onChange={changeQuery("b")}
      />
    </Layout>
  );
};
export default withRouter(Test);

1 Answer 1

7

I can use router.push to set the values but not sure if that's the way to do it correctly:

import { withRouter } from 'next/router';
import Layout from '../components/Layout';
const removeUndefined = o =>
  Object.entries(o)
    .filter(([, val]) => val!==undefined)
    .reduce((result, [key, val]) => {
      result[key] = val;
      return result;
    }, {});

const Test = ({ router }) => {
  const { pathname, query } = router;
  const { a, b } = query;
  const changeQuery = val => e =>
    router.push({
      pathname,
      query: removeUndefined({
        ...query,
        [val]: e.target.checked ? 1 : undefined,
      }),
    });
  return (
    <Layout>
      <pre>
        {JSON.stringify(query, undefined, 2)}
      </pre>
      a:
      <input
        type="checkbox"
        value="a"
        checked={a}
        onChange={changeQuery('a')}
      />
      b:
      <input
        type="checkbox"
        value="b"
        checked={b}
        onChange={changeQuery('b')}
      />
    </Layout>
  );
};
export default withRouter(Test);
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.