Skip to content

Instantly share code, notes, and snippets.

View isocroft's full-sized avatar
💯
Documenting Software...

Ifeora Okechukwu isocroft

💯
Documenting Software...
View GitHub Profile
@isocroft
isocroft / useQueryFromMap.tsx
Last active March 17, 2024 13:30
This is a custom hook that allows you to utilize a simple strategy pattern to select <@tanstack/react-query> `useQuery` custom hooks within a single component
import React, { useContext, useMemo } from "react";
import type { UseQueryResult } from "react-query";
type ReactQueryFetchStatus = "idle" | "loading" | "error" | "success";
export type UseQueryPackedUnion = "status" | "data";
/*
type ReactQueryFetchHook<F extends Array<unknown>, Q = any, P = any> = (...hookArguments: [...F, P?]) => UseQueryResult<Q> | Pick<UseQueryResult<Q>, UseQueryPackedUnion>
@isocroft
isocroft / assertionSignatureValidation.tsx
Created March 17, 2024 11:24
Using assertion signatures to validate data from external sources using the Yup validation/schema library
import Yup from "yup";
import type { InferType } from "yup";
const UserSchema = Yup.object({
name: Yup.string().required(),
email: Yup.string().email().required(),
fullname: Yup.string().required(),
title: Yup.string().required(),
gender: Yup.string().required().default("male"),
rating: Yup.number().min(1).max(10).required(),
@isocroft
isocroft / NextJSFormStepsWizard.tsx
Last active February 28, 2024 02:33
A custom NextJS component that makes setting up a step form wizard a breeze
import React, { useRef, useState, useEffect, useCallback, Children, isValidElement, cloneElement } from "react";
import Router from "next/router";
import { useIsFirstRender } from "react-busser";
export type FormStepComponentProps = {
currentStep: string | number,
stepsTotal: number,
onStepChange: (data: Record<string, any>, disableFormSubmission?: boolean, shouldNavigate?: boolean) => Promise<boolean>,
onFormChange: (htmlForm: HTMLFormElement, htmlFormValue: { [key: string]: any }) => number;
@isocroft
isocroft / axiosPoweredClient.ts
Created February 26, 2024 23:13
This is a simple Http client on the browser powered by axios library which makes it easy to make async requests
import axios, { AxiosError, AxiosResponse, AxiosRequestConfig, AxiosHeaders } from "axios";
import { API, authRefreshTokenStorageKeyName, authTokenStorageKeyName, userVerifyTokenStorageKeyName } from "@/constants";
import { handleLogout, isCORSViolation } from "./utils";
export type { AxiosError };
export interface OptionsArgs<BodyType, ParamType = any> {
body?: BodyType;
headers?: { [key: string]: any };
params?: ParamType,
@isocroft
isocroft / useReactQueryCache.ts
Created February 26, 2024 20:32
A custom ReactJS/NextJS hook based on @tanstack/react-query that queries the cache for the contents at a given query key
import { useQueryClient } from "@tanstack/react-query";
export function useReactQueryCache<D, E>(queryKey: unknown[] = []) {
const queryClient = useQueryClient();
const queryCache = queryClient.getQueryCache();
return queryCache.find<D, E>(queryKey);
};
@isocroft
isocroft / useNextJSPreviousRoute.ts
Created February 26, 2024 20:27
A custom NextJS hook that returns the previous route visited in a browser application
import { useRouter } from "next/router";
import { useRef } from "react";
export const useNexJSPreviousRoute = () => {
const router = useRouter();
const ref = useRef<string | null>(null);
router.events?.on("routeChangeStart", () => {
ref.current = router.asPath;
@isocroft
isocroft / useNextJSUnsavedChangesLock.tsx
Created February 26, 2024 20:24
A custom NextJS hook for handling unsaved changes in a browser application
import { useRouter } from "next/router";
import { useState, useEffect } from "react";
export const useNextJSUnsavedChangesLock = ({
promptText = "You have unsaved changes - are you sure you wish to leave this page?",
useBrowserPrompt = true,
unsavedChangesStatus = false
}: { promptText: string, useBrowserPrompt?: boolean, unsavedChangesStatus?: boolean }) => {
const router = useRouter();
router.beforePopState((state) => {
@isocroft
isocroft / extras.ts
Last active February 5, 2024 22:21
A collection of very useful helper functions for frontend work
import { lazy } from "react";
/**
* lazyWithRetry:
*
* @param {() => (() => JSX.Element)} componentImport
* @returns {() => JSX.Element}
*
* @see https://gist.github.com/raphael-leger/4d703dea6c845788ff9eb36142374bdb#file-lazywithretry-js
*
@isocroft
isocroft / react-testing-library-helpers.tsx
Last active January 18, 2024 16:53
Helper functions for react-testing-library to make writing tests a lot easier and faster while maintaining quality feedback
import React from "react";
import { Provider as ReactReduxProvider } from "react-redux";
import { IntlProvider as ReactIntlProvider } from "react-intl";
import { BrowserRouter, BrowserRouterProps, MemoryRouter, MemoryRouterProps, Router, RouterProps } from "react-router-dom";
import { History, LocationDescriptor, createBrowserHistory, createMemoryHistory } from "history";
import { render, RenderOptions, RenderResult } from "@testing-library/react";
import { renderHook, RenderHookResult, RenderHookOptions } from "@testing-library/react-hooks";
type Separate<F, O> = F extends O ? F : null;
type Writeonly<T> = Separate<keyof T, keyof Readonly<T>>;
@isocroft
isocroft / object-util.ts
Last active July 3, 2023 16:32
A ReactJS hook that filters any generic kind of list/array (of strings or of similar dictionary objects) using a text search term targeting one or more properties in the dictionary object in the list using 3 different text search algorithms (complete, fuzzy, specific) with options to extend with your custom text search algorithm
type Literal = unknown
export interface ReducableObject {
[key:string]: Literal | ReducableObject;
}
export function throttleFilterCallbackRoutine<S, N extends () => void> (
routine: (...args: [S]) => N,
routineArgs: [S],
interval = 500