Skip to content

Instantly share code, notes, and snippets.

@assertchris
Last active November 22, 2019 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save assertchris/823922d6857e73fdcb53c88eab3fdd8b to your computer and use it in GitHub Desktop.
Save assertchris/823922d6857e73fdcb53c88eab3fdd8b to your computer and use it in GitHub Desktop.
import { useState, useCallback } from "react"
import qs from "query-string"
const getQueryStringValue = function(router, key, initial) {
if (typeof router.query[key] !== "undefined") {
return router.query[key]
}
return initial
}
const setQueryStringValue = function(router, key, value) {
const string = qs.stringify({
...router.query,
[key]: value,
})
router.push(router.pathname + `?${string}`)
}
export const useQueryString = function(router, key, initial) {
const previous = getQueryStringValue(router, key, initial)
const [value, setValue] = useState(previous)
const onSetValue = useCallback(
next => {
setValue(next)
setQueryStringValue(router, key, next)
},
[key],
)
return [value, onSetValue]
}
import React, { Fragment, useEffect } from "react"
import Head from "next/head"
import { useRouter } from "next/router"
import { useQueryString } from "../hooks"
import { Document, Knobs } from "./components"
const Index = () => {
const router = useRouter()
const [showKnobs, setShowKnobs] = useQueryString(router, "show-knobs", "")
return (
<Fragment>
<Head>
<title>PDF Generator</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
</Head>
<Document />
{showKnobs ? (
<Fragment>
<button onClick={() => setShowKnobs("")}>hide knobs</button>
<Knobs />
</Fragment>
) : (
<button onClick={() => setShowKnobs("1")}>show knobs</button>
)}
</Fragment>
)
}
Index.getInitialProps = function() {
return {}
}
export default Index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment