Skip to content

reverb6821/cosmo-snippet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

63 Commits
 
 
 
 
 
 

Repository files navigation

JavaScript & TypeScript Snippets 🚀

This is a collection of useful and most common JavaScript, TypeScript, React, tanstack/react-query and zustand snippets for Visual Studio Code. These snippets speed up my regular development by providing quick access to commonly used functions and structures.

🛠️ Installation

To use these snippets in VS Code:

  1. Open the Command Palette (Ctrl + Shift + P).
  2. Type "Preferences: Configure User Snippets".
  3. Select "New Global Snippets File", or choose an existing snippet file.
  4. Copy and paste the snippets below into the .json file. Alternative, you can

🚀 Usage

Simply type the prefix in VS Code, press Tab, and the snippet will expand!

🔹 Available Snippets

Console Methods

  • clgconsole.log('data')
  • cerconsole.error('data')
  • cwarnconsole.warn('data')
  • cinfoconsole.info('data')
  • ctabconsole.table('data')

Functions & Interfaces

  • fnFunction Declaration
    function functionName(parameters) {
        // function body
    }
  • interfaceTypeScript Interface
    interface InterfaceName { property: type; }
  • arrowArrow Function
    const functionName = (parameters) => {
        // function body
    };

Loops & Array Methods

  • forloopfor (let i = 0; i < array.length; i++) { }
  • maparray.map(item => { })
  • filterarray.filter(item => { })
  • reducearray.reduce((acc, item) => { }, initialValue)
  • findarray.find(item => { })
  • includesarray.includes(value)
  • pusharray.push(item)
  • poparray.pop()
  • shiftarray.shift()
  • unshiftarray.unshift(item)
  • slicearray.slice(start, end)
  • splicearray.splice(start, deleteCount, item)
  • sortarray.sort((a, b) => a - b)
  • reversearray.reverse()

Object Methods

  • keysObject.keys(obj)
  • valuesObject.values(obj)
  • entriesObject.entries(obj)
  • assignObject.assign(target, source)
  • spread{ ...obj, newProperty: value }
  • destructconst { key1, key2 } = obj;
  • objconst obj = { key: value };

Asynchronous Code

  • asyncfnAsync Function
    async function functionName(parameters) {
        try {
            await task();
        } catch (error) {
            console.error(error);
        }
    }
  • promisePromise with .then/.catch
    new Promise((resolve, reject) => {
        // task
    })
    .then(result => console.log(result))
    .catch(error => console.error(error));

React Hooks

  • usestateuseState Hook
    const [state, setState] = useState(initialValue)
  • useeffectuseEffect Hook
      useEffect(() => {
      // side effects
      }, [dependencies])
  • usememouseMemo Hook
     const memoizedValue = useMemo(() => computeExpensiveValue, [dependencies])
  • userefuseRef Hook
    const refElement = useRef(null);
  • usecallbackuseCallback Hook
    const memoizedCallback = useCallback((args) => {
    // function body
    }, [dependencies]);
  • usereduceruseReducer Hook
    const [state, dispatch] = useReducer(reducerFunction, initialState);

React Function Components

  • fncFunction Component with TypeScript Interface
      import React from 'react';
    
      interface Props {
      exampleProp?: string;
      }
    
      function MyComponent({ exampleProp }: Props): JSX.Element {
      return (
          <div>
          {/* Your component code here */}
          </div>
      );
      }
    
      export default MyComponent;
  • fnc-queryFunction Component with Interface and React Query
     import React from 'react';
      import { useQuery } from '@tanstack/react-query';
    
      interface Props {
      exampleProp?: string;
      }
    
      function MyComponent({ exampleProp }: Props): JSX.Element {
      const { data, error, isLoading } = useQuery({
          queryKey: ['yourQueryKey'],
          queryFn: async () => {
          const res = await fetch('/api/endpoint');
          if (!res.ok) throw new Error('Network response was not ok');
          return res.json();
          },
      });
    
      if (isLoading) return <div>Loading...</div>;
      if (error) return <div>Error: {(error as Error).message}</div>;
    
      return (
          <div>
          {/* Render fetched data here */}
          <pre>{JSON.stringify(data, null, 2)}</pre>
          </div>
      );
      }
    
      export default MyComponent;
  • fnc-mutationFunction Component with Interface and useMutation
      import React from 'react';
      import { useMutation } from '@tanstack/react-query';
    
      interface Props {
      exampleProp?: string;
      }
    
      interface Payload {
      key: string;
      }
    
      function MyComponent({ exampleProp }: Props): JSX.Element {
      const mutation = useMutation({
          mutationFn: async (newData: Payload) => {
          const res = await fetch('/api/endpoint', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(newData),
          });
          if (!res.ok) throw new Error('Failed to submit');
          return res.json();
          },
          onSuccess: (data) => {
          console.log('Success:', data);
          },
          onError: (error) => {
          console.error('Error:', error);
          },
      });
    
      const handleSubmit = () => {
          mutation.mutate({ key: 'value' });
      };
    
      return (
          <div>
          <button onClick={handleSubmit} disabled={mutation.isPending}>
              {mutation.isPending ? 'Sending...' : 'Submit'}
          </button>
          {mutation.isError && <div>Error: {(mutation.error as Error).message}</div>}
          {mutation.isSuccess && <div>Success!</div>}
          </div>
      );
      }
    
      export default MyComponent;
  • fcFunction Component with Interface and useMutation
      import React from 'react';
     
    
      function MyComponent({ exampleProp }: Props): JSX.Element {
     
    
      return (
          <div>
    
          </div>
      );
      }
    
      export default MyComponent;
  • fc-queryFunctional Component with Interface and React Query
    import React, { FC } from 'react';
      import { useQuery } from '@tanstack/react-query';
    
      interface ComponentNameProps {
      exampleProp?: string;
      }
    
      const ComponentName: FC<ComponentNameProps> = ({ exampleProp }) => {
      const { data, error, isLoading } = useQuery({
          queryKey: ['yourQueryKey'],
          queryFn: async () => {
          const res = await fetch('/api/endpoint');
          if (!res.ok) throw new Error('Network response was not ok');
          return res.json();
          },
      });
    
      if (isLoading) return <div>Loading...</div>;
      if (error) return <div>Error: {(error as Error).message}</div>;
    
      return <div><pre>{JSON.stringify(data, null, 2)}</pre></div>;
      };
    
      export default ComponentName;
  • fc-mutationFunctional Component with Interface and useMutation
      import React, { FC } from 'react';
      import { useMutation } from '@tanstack/react-query';
    
      interface ComponentNameProps {
      exampleProp?: string;
      }
    
      const ComponentName: FC<ComponentNameProps> = ({ exampleProp }) => {
      const mutation = useMutation({
          mutationFn: async (newData) => {
          const res = await fetch('/api/endpoint', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(newData),
          });
          if (!res.ok) throw new Error('Failed to submit');
          return res.json();
          },
          onSuccess: (data) => console.log('Success:', data),
          onError: (error) => console.error('Error:', error),
      });
    
      const handleSubmit = () => mutation.mutate({ key: 'value' });
    
      return (
          <div>
          <button onClick={handleSubmit} disabled={mutation.isPending}>
              {mutation.isPending ? 'Sending...' : 'Submit'}
          </button>
          {mutation.isError && <div>Error: {(mutation.error as Error).message}</div>}
          {mutation.isSuccess && <div>Success!</div>}
          </div>
      );
      };
    
      export default ComponentName;

Zustand

  • zustandStoreTSZustand Store
      import { create } from 'zustand';
    
      interface StoreState {
      count: number;
      setCount: (value: number) => void;
      }
    
      const useStore = create<StoreState>((set) => ({
      count: 0,
      setCount: (value) => set({ count: value }),
      }));
    
      export default useStore;
  • zustandStoreTSPersistent Zustand Store
      import { persist, createJSONStorage } from 'zustand/middleware';
      import { create } from 'zustand';
    
      interface StoreState {
      count: number;
      setCount: (value: number) => void;
      }
    
      const useStore = create<StoreState>()(
      persist(
          (set) => ({
          count: 0,
          setCount: (value) => set({ count: value }),
          }),
          {
          name: 'my-store',
          storage: createJSONStorage(() => localStorage),
          }
      )
      );
    
      export default useStore;

Unit Testing with React Testing Library & Vitest

  • unittestBasic Unit Test for a Component
      import { render, screen } from '@testing-library/react';
      import { describe, it, expect } from 'vitest';
      import ComponentName from './ComponentName';
    
      describe('ComponentName', () => {
      it('renders correctly', () => {
          render(<ComponentName />);
          expect(screen.getByText('ExpectedText')).toBeInTheDocument();
      });
      });

About

A collection of useful snippets for JavaScript, TypeScript, React, and Zustand!

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published