### Node.js Middleware Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/deods.md Demonstrates a basic Node.js server setup with middleware callbacks that are invoked on hitting the root endpoint. Useful for handling request flows through a central point. ```javascript console.log("Server tS running on 8080"); ``` -------------------------------- ### Create and Use a JavaScript Proxy Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md This example demonstrates creating a JavaScript Proxy with custom 'get' and 'set' handlers. It then shows how accessing and modifying properties on the proxy triggers the defined handlers. This is useful for observing or controlling object interactions. ```javascript const person = { name: "John Doe", age: 42, nationality: "American" }; const personProxy = new Proxy(person, { get: (obj, prop) => { console.log(`The value of ${prop} is ${obj[prop]}`); return obj[prop]; }, set: (obj, prop, value) => { console.log(`Changed ${prop} from ${obj[prop]} to ${value}`); obj[prop] = value; } }); personProxy.name; personProxy.age = 43; ``` -------------------------------- ### Basic Singleton Implementation in JavaScript Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md This example demonstrates a basic Singleton class structure in JavaScript. It includes methods for getting the instance, retrieving the count, and incrementing/decrementing the count. Note that this initial version does not enforce a single instance. ```javascript class Counter { constructor() { this.count = 0; } getInstance() { return this; } getCount() { return this.count; } increment() { return ++this.count; } decrement() { return --this.count; } } ``` -------------------------------- ### Basic Promise Chain Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/parsing-of-the-html-on-the-main-thread-and-downloa.md Illustrates a basic Promise chain with `.then()` and `.catch()` for handling asynchronous operations. ```javascript .then(sortInput() ) .catch(err { console.log(err) }); ``` -------------------------------- ### Example Product Data Source: https://github.com/devinschumacher/patterns.dev/blob/main/application-shell-caching-with-service-workers-thi.md An array of product objects, each with an ID and name. Used to populate product lists. ```javascript products: [ { id: "1", name: "Blue Sneakers" }, { id: "2", name: "Leather Boots" } ] ``` -------------------------------- ### Class Component State Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/deods.md Example of a React class component managing input state. ```javascript class Input extends React.Component { state = { input: "" }; handleInput(e) { this.setState({ input: e.target.value }); } render() { return ; } } ``` -------------------------------- ### Named Export Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md Demonstrates how to export multiple functions using named exports in JavaScript. ```javascript export function multiply(x, y) { return x * y; } ``` ```javascript export function subtract(x, y) { return x - y; } ``` -------------------------------- ### Example: Creating Multiple Book Copies Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md Demonstrates adding multiple copies of different books to the library. Note that even with multiple copies, only one instance per ISBN is created. ```javascript const harryPotter = createBook('Harry Potter', 'J.K. Rowling', '978-0747532743'); const toKillAMockingbird = createBook('To Kill a Mockingbird', 'Harper Lee', '978-0061120084'); const theGreatGatsby = createBook('The Great Gatsby', 'F. Scott Fitzgerald', '978-0743273565'); addBook('Harry Potter', 'J.K. Rowling', '978-0747532743', false, 20); addBook('To Kill a Mockingbird', 'Harper Lee', '978-0061120084', false, 20); addBook('The Great Gatsby', 'F. Scott Fitzgerald', '978-0743273565', false, 20); addBook('Harry Potter', 'J.K. Rowling', '978-0747532743', false, 20); addBook('To Kill a Mockingbird', 'Harper Lee', '978-0061120084', false, 20); addBook('The Great Gatsby', 'F. Scott Fitzgerald', '978-0743273565', false, 20); ``` -------------------------------- ### Theme Context Provider Setup Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md Sets up the ThemeContext provider with theme state and a toggle function. Components wrapped by this provider can access theme values and the toggle function. ```javascript const [theme, setTheme] = useState("dark"); const toggleTheme = () => { setTheme(theme === "dark" ? "light" : "dark"); }; const providerValue = { theme: themes[theme], toggleTheme }; {children} ``` -------------------------------- ### Compound Component Example: Flyout Menu Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md Demonstrates the basic structure of a compound component using a Flyout menu. It shows how to export default components and their nested items. ```javascript export default function FlyoutMenu() { return ( Edit Delete ); } ``` -------------------------------- ### Rendering a List with ListItem Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md A basic example of rendering a list by mapping over an array and rendering a ListItem component for each element. ```javascript import ListItem from './ListItem'; export default function List() { return ( ); } ``` -------------------------------- ### Rendering a Simple HTML Structure Source: https://github.com/devinschumacher/patterns.dev/blob/main/code-where-rendertostaticmarkup-is-used-to-generat.md This example demonstrates rendering a basic HTML structure without any React-specific attributes, suitable for static content. ```javascript import { renderToStaticMarkup } from 'react-dom/server'; const element = (

Buy Plant

); const staticHtml = renderToStaticMarkup(element); console.log(staticHtml); ``` -------------------------------- ### Fetching Data with useQuery Hook Source: https://github.com/devinschumacher/patterns.dev/blob/main/deods.md An example of using the useQuery hook from Apollo Client to fetch data directly within a component. ```javascript import { useQuery } from '@apollo/client'; // ... other imports and component setup const { data, loading, error } = useQuery(YOUR_QUERY_HERE); ``` -------------------------------- ### Dynamic Import of Math Module Source: https://github.com/devinschumacher/patterns.dev/blob/main/deods.md This example demonstrates dynamic import. The 'math.js' module is only loaded when the user clicks the button, reducing initial page load time. The imported module's functions are then used. ```javascript const button = document.getElementById("myButton"); button.addEventListener("click", () => { import("./math.js").then((module) => { console.log("Add: ", module.add(1, 2)); console.log("Multiply: ", module.multiply(3, 2)); }); }); button.innerHTML = "Check the console"; ``` -------------------------------- ### Using InfiniteLoader with react-virtualized components Source: https://github.com/devinschumacher/patterns.dev/blob/main/parsing-of-the-html-on-the-main-thread-and-downloa.md This example demonstrates the integration of InfiniteLoader with components from react-virtualized, similar to how it might be used in a demo application for The Movie Database. It outlines the props for managing item loading and rendering within a virtualized grid. ```jsx {({ onItemsRendered, ref }) => ( {this.renderCell} )} ``` -------------------------------- ### Icon Component Usage Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md A basic example of rendering an Icon component within a div. This snippet is minimal and assumes the Icon component is defined elsewhere. ```javascript return (
) ``` -------------------------------- ### Applying the withLoader HOC to DogImages Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This example shows how to wrap the DogImages component with the withLoader HOC, specifying the API endpoint for fetching dog images. The fetched data will be available as a 'data' prop in DogImages. ```javascript import React, { useState, useEffect } from "react"; import withLoader from "./withLoader"; function DogImages(props) { return ( props.data.message.map((dog, index) => ( Dog )) ); } export default withLoader( DogImages, "https://dog.ceo/api/breed/labrador/images/random/6" ); ``` -------------------------------- ### Basic ES2015 Module Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md A simple ES2015 module named math.js that exports a function to add two numbers. Declarations are scoped to the module by default. ```javascript export function add(a, b) { return a + b; } ``` -------------------------------- ### Apollo Hooks Example with useMutation Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This example shows how to use the useMutation hook from '@apollo/react-hooks' to handle mutations in a functional React component. It manages local state for the input field. ```javascript import React, { useState } from "react"; import { useMutation } from "@apollo/react-hooks"; import "./styles.css"; function Input() { const [message, setMessage] = useState(""); const [addMessage] = useMutation(ADD_MESSAGE, { variables: { message }, }); return (
setMessage(e.target.value)} placeholder="Type something..." />
); } ``` -------------------------------- ### Creating a Basic Proxy with Get Interception Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md This snippet demonstrates how to create a proxy that intercepts property access. It logs a message when a non-existent property is accessed on the target object. ```javascript const person = { name: "John Doe", age: 30 }; const handler = { get(target, prop) { if (!(prop in target)) { console.log(`Hmm... this property doesn't seem to exist on the target object`); } console.log(`The value of ${prop} is ${target[prop]}`); return target[prop]; } }; const personProxy = new Proxy(person, handler); ``` -------------------------------- ### Basic Next.js Static Content Rendering Source: https://github.com/devinschumacher/patterns.dev/blob/main/application-shell-caching-with-service-workers-thi.md This example demonstrates a basic Next.js page that will be pre-rendered into an HTML file at build time. It's suitable for static content like 'About Us' or 'Contact Us' pages. ```javascript pages/about.js ``` -------------------------------- ### RxJS Dragging Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md Logs whether a user is dragging in the document using RxJS observables. Requires RxJS and RxJS operators. ```javascript import { fromEvent, merge } from "rxjs"; import { sample, mapTo } from "rxjs/operators"; merge( fromEvent(document, "mousedown").pipe(mapTo(true)), fromEvent(document, "mousemove").pipe(mapTo(true)), fromEvent(document, "mouseup").pipe(mapTo(false)).pipe(sample(fromEvent(document, "mouseup"))) ).subscribe(isDragging => { console.log("Are you dragging?", isDragging); }); ``` -------------------------------- ### JavaScript Prototype Chain Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md Illustrates how JavaScript walks the prototype chain to find properties. When a property is not found on the object itself, it recursively checks the object pointed to by `__proto__`. ```javascript class Dog { constructor(name) { this.name = name; } bark() { console.log("Woof!"); } } class SuperDog extends Dog { constructor(name) { super(name); } } const dog = new SuperDog("Buddy"); dog.bark(); ``` -------------------------------- ### Composing withLoader and withHover HOCs Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This example demonstrates composing two HOCs, `withLoader` and `withHover`, to enhance the `DogImages` component. The composed HOC provides both data loading and hover state management. ```javascript import React from 'react'; import withLoader from "./withLoader"; import withHover from "./withHover"; function DogImages(props) { return (
{props.hovering && Hovering!}
); } export default withHover( withLoader(DogImages, "https://dog.ceo/api/breed/labrador/images/random/6") ); ``` -------------------------------- ### Apollo Client graphql() HOC Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This snippet demonstrates how to use the graphql() HOC to wrap a React component, making Apollo Client data available within it. Ensure 'react-apollo' is imported. ```javascript import { graphql } from "react-apollo"; class Input extends React.Component { render() { return (
); } } export default graphql(ADD_MESSAGE)(Input); ``` -------------------------------- ### React State Management with Hooks Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md Example demonstrating how to manage local component state using React Hooks like useState. This is suitable for managing form inputs or simple UI states within a component. ```javascript const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); ``` -------------------------------- ### Mark Components for Hydration with withHydration Source: https://github.com/devinschumacher/patterns.dev/blob/main/ease-of-distribution-just-like-ssg-sites-issg-site.md Use the `withHydration` API to designate interactive components for prioritized hydration. This example shows how `HydratedTeaser` components are marked for early hydration. ```javascript import { withHydration } from "next-super-performance"; const HydratedTeaser = withHydration(Teaser); export default function Body() { return (
); } ``` -------------------------------- ### Add a Book Copy to the Library Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This function adds a copy of a book to the `bookList`. It utilizes `createBook` to get or create a book instance and then adds sales and availability details for the specific copy. ```javascript function addBook(title, author, tsbn, availability, sales) { book = { ... createBook(title, author, tsbn), sales, availibility, isbn } bookList.pubsoohk(); bookList; return book; } ``` -------------------------------- ### Flyout Menu Component using Compound Pattern Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This example demonstrates a Flyout menu component built using the Compound Component pattern. It utilizes nested components like FlyOut.Toggle, FlyOut.List, and FlyOut.Item to create a functional UI element without managing state in the parent FlyoutMenu component. ```jsx import React from "react"; import FlyOut from './FlyOut'; export default function FlyoutMenu() { return ( Edit Delete ) } ``` -------------------------------- ### Using the Singleton Counter Instance Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md Demonstrates how to use the Singleton Counter. It shows creating an instance and then using its methods. Note that attempting to create a second instance will throw an error. ```javascript const counter = new Counter(); // Attempting to create another instance will throw an error: // const anotherCounter = new Counter(); console.log(counter.getCount()); // 0 counter.increment(); console.log(counter.getCount()); // 1 ``` -------------------------------- ### Define Proxy Handlers for Get and Set Operations Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md This snippet defines the 'get' and 'set' handlers for a JavaScript Proxy. The 'get' handler logs the property being accessed, and the 'set' handler logs changes to properties. Use this to intercept and log property interactions. ```javascript get: (obj, prop) => { console.log(`The value of ${prop} is ${obj[prop]}`); return obj[prop]; }, set: (obj, prop, value) => { console.log(`Changed ${prop} from ${obj[prop]} to ${value}`); obj[prop] = value; } ``` -------------------------------- ### React Class Component Example Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md An example of a React class component defined using an ES6 class. Class components have their own state and lifecycle methods. ```javascript class Hello extends React.Component { render() { return

Hello, my name is {this.props.name}

; } } ``` -------------------------------- ### Instantiate Dog and Use Mixin Methods Source: https://github.com/devinschumacher/patterns.dev/blob/main/deods.md Creates a new Dog instance and demonstrates calling methods inherited through the mixin pattern. ```javascript const myDog = new Dog("Daisy"); myDog.bark(); myDog.walk(); ``` -------------------------------- ### Instantiating and Accessing Singleton Instances Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md Demonstrates how to create two variables that appear to be separate instances but actually point to the same Singleton instance. Calling `getInstance()` on each returns a reference to the single shared instance. ```javascript const counterl = new Counter(); const counter2 = new Counter(); console.log(counterl.getInstance() === counter2.getInstance()); ``` -------------------------------- ### Class Component State Update Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md Example of updating state within a traditional React class component. ```javascript this.setState(({ count }) => ({ count: count + 1 })); ``` -------------------------------- ### Setting up Observer Subscription Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md Demonstrates how to subscribe both a logger and a toast notification function to an observable instance. This ensures both functions are called when the observable notifies. ```javascript observable.subscribe(logger); observable.subscribe(notify); ``` -------------------------------- ### Providing FlyOutContext Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This snippet shows how to wrap children with the FlyOutContext.Provider to make the context available. It initializes the 'open' state to false. ```javascript const [open, setOpen] = useState(false); return ( {props.children} ) ``` -------------------------------- ### DogImagesContainer Component (Class-based) Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md This component fetches dog images using componentDidMount and manages the state. It's a classic example of a container component. ```javascript import React from "react"; import DogImages from "./DogImages"; class DogImagesContainer extends React.Component { state = { dogs: [], }; componentDidMount() { fetch("https://dog.ceo/api/breed/labrador/images/random/6") .then((res) => res.json()) .then(({ message }) => this.setState({ dogs: message })); } render() { return ; } } ``` -------------------------------- ### React Component with Input Handling Source: https://github.com/devinschumacher/patterns.dev/blob/main/deods.md A basic React component that handles user input. It's designed to be part of a larger state management example. ```jsx return ( Hello, my name is {props.name}; } ``` -------------------------------- ### Open IndexedDB using Window Mixin Source: https://github.com/devinschumacher/patterns.dev/blob/main/deods.md Demonstrates opening an IndexedDB database using a method available from the WindowOrWorkerGlobalScope mixin. ```javascript window.indexedDB.open("toDoList"); ``` -------------------------------- ### Pre-render Individual Pages with getStaticPaths Source: https://github.com/devinschumacher/patterns.dev/blob/main/application-shell-caching-with-service-workers-thi.md Combine getStaticPaths with dynamic routes to pre-render pages for specific items at build time. Fetch all possible IDs to define which pages should be generated. ```javascript export async function getStaticPaths() { const products = await fetch('YOUR_API_ENDPOINT').then(res => res.json()); const paths = products.map((product) => ({ params: { id: product.id.toString() }, })); return { paths, fallback: false, // Can also be true or 'blocking' }; } ``` -------------------------------- ### Using Renamed Functions and Other Exports Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md Demonstrates calling functions that have been imported and renamed, as well as other exported functions. Ensure all necessary functions are imported before use. ```javascript addValues(7, 8); multiplyValues(2, 3); Subtract(10, 3); Square(3); ``` -------------------------------- ### DogImages Presentational Component using Custom Hook Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md This presentational component now uses the custom useDogImages hook to get the data, eliminating the need for a separate container component. ```javascript import React from "react"; import useDogImages from "./useDogImages"; function DogImages() { const dogs = useDogImages(); return (
{dogs.map((dog, i) => ( Dog ))}
); } ``` -------------------------------- ### Exporting a Singleton Instance Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md This code snippet shows how to create a singleton instance and export it as the default export from a module. This is a common way to manage singleton state in JavaScript applications. ```javascript import Counter from './counter.js'; const counter = Counter.getInstance(); // Add event listener to red button redButton.addEventListener('click', () => { counter.increment(); console.log(counter.getCount()); }); // Add event listener to blue button blueButton.addEventListener('click', () => { counter.increment(); console.log(counter.getCount()); }); console.log(counter.getCount()); // 0 ``` -------------------------------- ### Integrating useKeyPress Hook in an Input Component Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This example shows how to use the `useKeyPress` hook within a React component to conditionally log messages to the console when specific keys are pressed. ```javascript import React from 'react'; import useKeyPress from './useKeyPress'; export default function Input() { const [value, setValue] = React.useState(''); const gqPressed = useKeyPress('g'); const lPressed = useKeyPress('l'); const wPressed = useKeyPress('w'); React.useEffect(() => { if (gqPressed) console.log('g pressed'); }, [gqPressed]); React.useEffect(() => { if (lPressed) console.log('l pressed'); }, [lPressed]); React.useEffect(() => { if (wPressed) console.log('w pressed'); }, [wPressed]); return ( setValue(e.target.value)} /> ); } ``` -------------------------------- ### Creating a 'SuperDog' by extending 'Dog' class Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md Illustrates how to create a new class 'SuperDog' that inherits from the 'Dog' class using ES6 class syntax. This allows 'SuperDog' instances to access 'Dog' methods and add their own unique functionalities like 'fly'. ```javascript class SuperDog extends Dog { constructor(name) { super(name); } fly() { console.log("Flying now!"); } } ``` -------------------------------- ### Using useReducer for State Management Source: https://github.com/devinschumacher/patterns.dev/blob/main/parsing-of-the-html-on-the-main-thread-and-downloa.md A basic example of using the `useReducer` hook for state management within a React component. This pattern is often used for more complex state logic. ```javascript const EmojiPicker = React.lazy(() => import(/* webpackPrefetch: true */ './EmojiPicker.js')); function App() { const [state, dispatch] = useReducer(reducer, initialState); return (
); } ``` -------------------------------- ### User Class with Constructor and fullName Method Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This defines a `User` class with a constructor to initialize properties and a `fullName` method to return the user's full name. It demonstrates a class-based approach that can also be used in a factory-like manner. ```javascript class User { constructor(firstName, LastName, email) { this.firstName = firstName; this.LastName = LastName; this.ematl = email; } fullName() { return `${this.firstName} ${this.LastName}`; } } const user1 = new User("John", "Doe", "john@doe.com"); ``` -------------------------------- ### ES6 Module Import for Tree Shaking Source: https://github.com/devinschumacher/patterns.dev/blob/main/parsing-of-the-html-on-the-main-thread-and-downloa.md Demonstrates how to import modules using ES2015 syntax. Only modules imported this way can be tree-shaken. ```javascript import { nap } from "./utils.js"; nap(); ``` -------------------------------- ### Input Component with State Handling Source: https://github.com/devinschumacher/patterns.dev/blob/main/deods.md A stateful Input component in React that manages its own value. This example highlights the need for lifting state when sibling components require access to this value. ```jsx Input({ value, handleChange }) { value={value} onChange={e handleChange(e.target.value) }; ``` -------------------------------- ### Rendering Application with React Source: https://github.com/devinschumacher/patterns.dev/blob/main/ease-of-distribution-just-like-ssg-sites-issg-site.md This snippet shows a basic render function, likely from a React application, which is a prerequisite for client-side hydration. It's the entry point for rendering the application on the client. ```javascript render(app) ``` -------------------------------- ### Singleton Counter Class in JavaScript Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md Implements the Singleton pattern for a counter. Ensures only one instance of the Counter class can be created and provides methods to get the instance, increment, decrement, and retrieve the count. ```javascript class Counter { constructor() { if (Counter.instance) { throw new Error("You can only create one instance!"); } this.counter = 0; Counter.instance = this; } static getInstance() { return this.instance; } getCount() { return this.counter; } increment() { this.counter++; } decrement() { this.counter--; } } ``` -------------------------------- ### FlyoutMenu Component Structure Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This example demonstrates how to import and use the FlyOut component, including its Toggle sub-component, within a React functional component. This simplifies usage by only requiring the import of the main FlyOut component. ```javascript import React from "react"; import { FlyOut } from "./FlyOut"; export default function FlyoutMenu() { return ( ); } ``` -------------------------------- ### Listening to Input Changes with useEffect Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md Use the useEffect hook with an input value in its dependency array to trigger side effects when the input changes. This example logs the input value to the console on every change. ```javascript useEffect(() => { console.log(`The user typed ${input}`); }, [input]); ``` -------------------------------- ### Implementing Set Interception for Data Validation Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md This example shows how to use the 'set' trap in a proxy handler to validate incoming data before modifying the target object. It includes specific validation for 'age' and 'name' properties. ```javascript const handler = { get(target, prop) { console.log(`The value of ${prop} is ${target[prop]}`); return target[prop]; }, set(obj, prop, value) { if (prop === "age" && typeof value === "number") { console.log(`Sorry, you can only pass numeric values for age.`); } else if (prop === "name" && value.length < 3) { console.log(`You need to provide a valid name.`); } else { console.log(`Changed ${prop} from ${obj[prop]} to ${value}.`); return Reflect.set(obj, prop, value); } } }; ``` -------------------------------- ### Calling Default and Named Exports Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md Shows how to import and use both a default export and named exports from a module. The default export can be imported directly, while named exports require specific import syntax. ```javascript import add, { multiply } from "./math.js"; add(8, 9); multiply(8, 9); ``` -------------------------------- ### Importing All Exports Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md Shows how to import all named and default exports from a module into a single object. ```javascript import * as math from 'module'; ``` -------------------------------- ### PlaceOrderCommand Implementation Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md Implements the PlaceOrderCommand, which adds an order to the manager's list and logs a success message. It takes the order details and ID as arguments. ```javascript class PlaceOrderCommand extends Command { constructor(order, id) { super((orders) => { orders.push({ order, id }); console.log(`You have successfully ordered ${order} (${id});`); }); } } ``` -------------------------------- ### Testing Singleton Increment Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md This test suite demonstrates the challenges of testing Singletons. Tests must be ordered correctly, and the Singleton's state must be reset between tests to avoid cascading failures. ```javascript import Counter from "./src/counterTest"; test( "incrementing 1 time should be 1", () => { Counter.increment(); expect(Counter.getCount()).toBe(1); }); test( "incrementing 3 extra times should be 4", () => { Counter.increment(); Counter.increment(); Counter.increment(); expect(Counter.getCount()).toBe(4); }); test("decrementing 1 times should be 3", () => { Counter.decrement(); expect(Counter.getCount()).toBe(3); }); ``` -------------------------------- ### Handling Window Resize with State Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This snippet demonstrates updating component state with the window's inner width. It assumes a `useCounter` hook is available and `this.setState` is used, suggesting a class component context or a specific setup. ```javascript handleResize = () => { const counter = useCounter(); this.setState({ width: .innerWidth }); } ``` -------------------------------- ### Integrating useDogImages Hook Source: https://github.com/devinschumacher/patterns.dev/blob/main/container-components-components-that-care-about-wh.md Demonstrates how to use the useDogImages hook within a component to fetch and manage dog image data, then pass it to a presentational component. ```javascript const DogApp = () => { const dogs = useDogImages(); return ; }; ``` -------------------------------- ### Integrating useHover Hook into DogImages Component Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md Demonstrates how to use the useHover hook directly within the DogImages component to manage hover effects, eliminating the need for a separate HOC. ```javascript import React from 'react'; import withLoader from './withLoader'; import useHover from './useHover'; function DogImages(props) { const [hoverRef, hovering] = useHover(); return (
{hovering &&
Hovering!
}
{props.data.message.map((dog, index) => ( Dog ))}
); } export default withLoader( DogImages, "https://dog.ceo/api/breed/labrador/images/random/6" ); ``` -------------------------------- ### Handle Data Stream for Server Rendering Source: https://github.com/devinschumacher/patterns.dev/blob/main/reduces-bundle-size-code-splitting-automatically-r.md This snippet handles incoming data chunks from a stream during server rendering. It logs the start time and pipes the stream to the response, disabling the default end behavior to allow further stream processing. ```javascript stream.on( "data", function handleData { console.log( "Render Start: ", Date. stream.pipe(response, { end: false }); }); ``` -------------------------------- ### Using Object.create to Set Prototype Source: https://github.com/devinschumacher/patterns.dev/blob/main/page-1.md Demonstrates creating a new object (`pet1`) with an explicit prototype (`dog`). This allows `pet1` to inherit properties like `bark` from `dog` without having them directly defined on `pet1`. ```javascript const dog = { bark() { console.log("Woof!"); } }; const pet1 = Object.create(dog); pet1.bark(); console.log("Direct properties on pet1: ", Object.keys(pet1)); console.log("Properties on pet1's prototype: ", Object.keys(pet1.__proto__)); ``` -------------------------------- ### Using React.lazy and Suspense for Code Splitting Source: https://github.com/devinschumacher/patterns.dev/blob/main/parsing-of-the-html-on-the-main-thread-and-downloa.md Demonstrates how to implement code-splitting in a React application using `React.lazy` for dynamic component loading and `Suspense` for handling loading states. This approach separates components into distinct JavaScript chunks. ```javascript import React lazy, Suspense } from 'react'; import MessageList from './MessageList'; import MessageInput from './MessageInput' ; ``` -------------------------------- ### Generate Dynamic Paths for SSG Source: https://github.com/devinschumacher/patterns.dev/blob/main/application-shell-caching-with-service-workers-thi.md Use getStaticPaths to define dynamic routes for SSG. Set fallback to false to ensure that any path not generated at build time will result in a 404 error. ```javascript export async function getStaticPaths() { const paths = products.map((product) => ({ params: { id: product.id } })) // fallback: false means pages that don’t have the correct id will 404. return { paths, fallback: false } } ``` -------------------------------- ### Create a New Book Instance Source: https://github.com/devinschumacher/patterns.dev/blob/main/the-method-with-which-we-can-update-the-state.md This function creates a new book instance if it doesn't already exist. It's used internally by `addBook` to ensure a single instance per ISBN. ```javascript function createBook(title, author, isbn) { existingBook = books.has(tsbn); if (existingBook) { books.get(isbn); } else { exele) <4 Book(title, author, isbn); books.set(isbn, book); } } ```