Last active
March 13, 2024 11:33
-
-
Save shlomoweb1/c45a99c09771dafc226f8ba51d3f3497 to your computer and use it in GitHub Desktop.
A vscode custom snippest creating context with reducer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "TS + React Context Provider + reducer": { | |
| "prefix": "rcp", | |
| "body": [ | |
| "import React, { createContext, useReducer, useContext } from 'react';", | |
| "import type { PropsWithChildren, FC } from 'react';", | |
| "", | |
| "// eslint-disable-next-line @typescript-eslint/no-empty-interface", | |
| "interface $1ProviderProps extends PropsWithChildren {", | |
| " // Provider Props goes here", | |
| "}", | |
| "", | |
| "// eslint-disable-next-line @typescript-eslint/no-empty-interface", | |
| "interface $1State {", | |
| " // Define your state properties here", | |
| "}", | |
| "", | |
| "interface $1ContextType {", | |
| " // Define your context properties here", | |
| " state: $1State;", | |
| " dispatch: React.Dispatch<$1Actions>;", | |
| "}", | |
| "", | |
| "// Add more action by adding pipe ( | )", | |
| "type $1Actions = {type: 'SET_ALL', payload: $1State};", | |
| "", | |
| "// set all mutation in reducer", | |
| "const $1Reducer = (state: $1State, action: $1Actions) => {", | |
| " const {type, payload} = action;", | |
| " switch (type) {", | |
| " case 'SET_ALL': return { ...state, payload};", | |
| " default:", | |
| " return state", | |
| " }", | |
| "}", | |
| "", | |
| "export const ${1/(.*)/${1:/capitalize}/}Context = createContext<$1ContextType | undefined>(undefined);", | |
| "", | |
| "export const ${1/(.*)/${1:/capitalize}/}ContextProvider: FC<$1ProviderProps> = ({ children }) => {", | |
| "", | |
| " // set all initial values, don't forgot to update TS", | |
| " const $1InitalValues = {}", | |
| "", | |
| " const [state, dispatch] = useReducer($1Reducer, $1InitalValues);", | |
| "", | |
| " return (", | |
| " <${1/(.*)/${1:/capitalize}/}Context.Provider value={{state, dispatch}}>", | |
| " {children}", | |
| " </${1/(.*)/${1:/capitalize}/}Context.Provider>", | |
| " );", | |
| "};", | |
| "", | |
| "export const use${1/(.*)/${1:/capitalize}/} = ()=>{", | |
| " const context = useContext(${1/(.*)/${1:/capitalize}/}Context)", | |
| " if(!context) {", | |
| " throw new Error('use${1/(.*)/${1:/capitalize}/} must be used within a ${1/(.*)/${1:/capitalize}/}Context provider!')", | |
| " }", | |
| " return context", | |
| "}" | |
| ], | |
| "description": "Create a React Context provider with reducer (for nextjs)" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment