Quantcast
Channel: Recent Gists from assertchris
Viewing all articles
Browse latest Browse all 30

hooks.js

$
0
0
hooks.js
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]
}
index.js
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

Viewing all articles
Browse latest Browse all 30

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>