Last active
July 25, 2022 07:26
-
-
Save bel0v/ad9f047bbfe7711d966a64f5f77cab07 to your computer and use it in GitHub Desktop.
VsCode snippets
This file contains 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
{ | |
"context-hook": { | |
"prefix": "context", | |
"body": [ | |
"import React, {useState, createContext, useContext} from 'react'", | |
"", | |
"interface ${1/(.*)/${1:/capitalize}/}ContextAPI {", | |
" $1: number", | |
" set${1/(.*)/${1:/capitalize}/}: (data: number) => void", | |
"}", | |
"type ${1/(.*)/${1:/capitalize}/}ProviderProps = {children: React.ReactNode}", | |
"", | |
"const ${1/(.*)/${1:/capitalize}/}Context = createContext<${1/(.*)/${1:/capitalize}/}ContextAPI|undefined>(undefined)", | |
"", | |
"export const ${1/(.*)/${1:/capitalize}/}Provider = ({children}: ${1/(.*)/${1:/capitalize}/}ProviderProps) => {", | |
" const [$1, set${1/(.*)/${1:/capitalize}/}] = useState(0)", | |
" const value = {$1, set${1/(.*)/${1:/capitalize}/}}", | |
" return <${1/(.*)/${1:/capitalize}/}Context.Provider value={value}>{children}</${1/(.*)/${1:/capitalize}/}Context.Provider>", | |
"}", | |
"", | |
"export function use${1/(.*)/${1:/capitalize}/}() {", | |
" const context = useContext(${1/(.*)/${1:/capitalize}/}Context)", | |
" if (context === undefined) {", | |
" throw new Error('use${1/(.*)/${1:/capitalize}/} must be used within a ${1/(.*)/${1:/capitalize}/}Provider')", | |
" }", | |
" return context", | |
"}", | |
"" | |
], | |
"description": "Creates React context hook blueprint" | |
} | |
} |
installation: Cmd+shift+P -> "Preferences: configure user snippets" -> "New global snippets file"
Updated gist: createContext
with initial undefined
value. Otherwise context === undefined
check doesn't make sense.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gist.mp4