Skip to content

Instantly share code, notes, and snippets.

@alex-cory
Created October 25, 2021 00:54
Show Gist options
  • Save alex-cory/f7ffca60dbb52fcfce7f472d29c2ebf1 to your computer and use it in GitHub Desktop.
Save alex-cory/f7ffca60dbb52fcfce7f472d29c2ebf1 to your computer and use it in GitHub Desktop.
/* Syntax */
import useRouter, { routes } from 'use-next-router'
// see this to implement: https://stackoverflow.com/questions/67764930/proxy-route-strings
// routes.api.posts => '/api/posts'
// routes.api.posts({ postId: 'ID' }) => '/api/posts/ID'
// routes.api.posts({ postId: 'ID' }).query({ name: 'alex' }) => '/api/posts/ID?name=alex'
// routes.api.posts.query({ name: 'alex' }) => '/api/posts?name=alex'
// routes.api.profiles({ profileId: 'ID' }).posts({ postId: 'ID' }).query({ name: 'alex' }) => '/api/profiles/ID/posts/ID?name=alex'
const Test = () => {
useEffect(() => {
const res = await fetch(routes.api.posts({ postId: 'some post id' }))
}, [])
const { push } = useRouter()
// back defaults to { shallow: true }
// and if 1st arg is a route default to that when clicking back
// if nothing in session storage, otherwise use browser's back
// push deaults to { shallow: true }
return <>
<div onClick={() => push(routes.tests)} />
<div onClick={() => back(routes.fallback)} />
</>
}
@alex-cory
Copy link
Author

See how this can be done using JS Proxy here in this stackoverflow question I asked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment