Skip to content

Instantly share code, notes, and snippets.

View akellbl4's full-sized avatar

Paul akellbl4

View GitHub Profile
@akellbl4
akellbl4 / customErrorHandling.ts
Created February 28, 2023 15:17
Custom error handling
class MyCustomError extends Error {
customField?: string
constructor(msg: string, customData: Record<string, string>) {
super(msg)
this.customField = customData.customField
}
}
try {
throw new MyCustomError('Custom Error', { customField: 'additional data' })
// pages/params.jsx
import Router, { useRouter } from 'lib/router'
function MyComponent() {
const { query } = useRouter()
function handleSubmit(evt) {
const params = new FormData(evt.currentTarget).getAll("fruits");
evt.preventDefault();
// lib/router.js
import NextRouter from 'next/router'
function push(url, opts) {
return NextRouter.push(url, null, opts)
}
const Router = {
...NextRouter,
push,
// pages/params.jsx
import Router from 'next/router'
import { useRouter } from 'lib/router'
function MyComponent() {
const { query, pathname } = useRouter()
function handleSubmit(evt) {
const params = new FormData(evt.currentTarget).getAll("fruits");
evt.preventDefault();
// lib/router.js
import { useRouter as useNextRouter } from 'next/router'
export function useRouter() {
const router = useNextRouter()
const [pathname, queryString = ''] = router.asPath.split('?')
return Object.assign(router, { pathname, queryString })
}
// pages/params.jsx
import Router from 'next/router'
function MyComponent() {
const handleClick = useCallback(() => {
// some logic
Router.push('/profile')
}, [])
useEffect(() => {
// pages/params.jsx
import { useEffect, useCallback } from 'react'
import { useRouter } from 'next/router'
function MyComponent() {
const { push } = useRouter()
const handleClick = useCallback(() => {
// some logic
push('/profile')
}, [push])
import Link from 'next/link'
// Before
function MyComponent() {
return (
<Link href="/posts/[post]" as="/posts/blog-post">
Blog post
</Link>
)
}
// Redirect
export function getServerSideProps() {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
@akellbl4
akellbl4 / profile.js
Created March 7, 2021 10:16
Code example for the article: "Why I got rid of getInitialProps on my work Next.js project"
async function fetchUser(params) {
const res = await fetch('https://example.com/api/user', params);
const data = await res.json();
return data;
}
async function fetchUserFromServer(ctx) {
const { token } = ctx.req.cookies;
const user = await fetchUser({ headers: { Authorization: `Bearer ${token}` } });