Skip to content

Instantly share code, notes, and snippets.

@mrcoles
mrcoles / use-intersection-observer.ts
Last active December 20, 2021 06:05
A simple hook for running an IntersectionObserver inside a React FunctionComponent
import { useEffect, useRef } from 'react';
export type OnIntersect = (elt: HTMLElement) => void;
/**
* Hook for running an IntersectionObserver.
* @param onIntersect this is used in the deps of useEffect, you can
* employ useCallback to prevent it from running
* after every render
* @param args
@mrcoles
mrcoles / airtable_escape.py
Last active December 26, 2021 19:24
A helper function for escaping variables passed into formulas in the Airtable API
from typing import Any, Optional, Union
from decimal import Decimal
class AirtableBadTypeException(Exception):
def __init__(self, val: Any):
self.val = val
super().__init__(f"unexpected type variable type: {type(val)}")
@mrcoles
mrcoles / dynamodb-auto-paginate-scan.ts
Last active March 29, 2021 02:20
Snippet for doing auto-pagination of a DynamoDB scan with an async generator in NodeJS
import { DocumentClient } from "aws-sdk/lib/dynamodb/document_client";
export async function* autoPaginateScan<I extends DocumentClient.AttributeMap>(
docClient: DocumentClient,
params: DocumentClient.ScanInput
) {
while (true) {
const data = await docClient.scan(params).promise();
if (data.Items && data.Items.length) {
@mrcoles
mrcoles / BlockUnload.tsx
Created August 24, 2020 18:29
A simple React component meant for form editing that will conditionally block page unloads and React Router navigation
import React from 'react';
import { useBeforeunload } from 'react-beforeunload';
import { Prompt } from 'react-router';
const DEFAULT_MESSAGE = 'You will lose unsaved changes if you leave this page.';
type BlockUnloadProps = {
when?: boolean;
message?: string;
};
@mrcoles
mrcoles / state-hooks.ts
Last active May 26, 2020 15:19
Helpful React hooks (for now just one…)
import { useState, Dispatch, SetStateAction } from 'react';
export const useUpdateState = <S extends object>(
defaultState: S
): [S, (newState: Partial<S>) => void, Dispatch<SetStateAction<S>>] => {
const [state, setState] = useState(defaultState);
const updateState = (newState: Partial<S>) =>
setState((prevState) => ({ ...prevState, ...newState }));
@mrcoles
mrcoles / djstripe_sync_webhook.py
Created May 22, 2020 16:01
A Django command function for syncing Stripe webhook events with your local server that happened while it wasn’t running
import json
from traceback import format_exc
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from djstripe import settings as djstripe_settings
from djstripe.models import Event, WebhookEventTrigger
from djstripe.signals import webhook_processing_error
# from djstripe.utils import convert_tstamp # convert stripe timestamps to datetimes
@mrcoles
mrcoles / stripe-pagination-exploration.md
Last active June 5, 2020 17:06
A look into how Stripe pagination filters and orders results when using pagination

Stripe Pagination Exploration

stripe.Event.list()

  • results: all events
  • order: created desc (most recent to oldest)

stripe.Event.list(ending_before=evt_id)

  • result: events that are newer than evt_id (created at a later time than evt_id)
@mrcoles
mrcoles / draw-on-sids-canvas.js
Created April 27, 2020 16:21
Code to automate drawing on the canvas element on Sid’s website (using simulated mouse events).
var target = document.querySelector('canvas');
var input = document.querySelector('input.jscolor');
var body = document.body;
var rect = target.getBoundingClientRect();
var irect = input.getBoundingClientRect();
var brect = document.body.getBoundingClientRect();
var simulateMouseEvent = function simulateMouseEvent(type, point, elt, eltRect) {
elt = elt || target;
@mrcoles
mrcoles / make-axios-request-config.ts
Created April 8, 2020 14:55
An example of making an AxiosRequestConfig object to do a multipart/form-data request
import axios, {
AxiosRequestConfig,
Method,
} from 'axios';
export const makeAxiosRequestConfig = (
method: Method,
path: string,
data?: { [key: string]: any },
@mrcoles
mrcoles / routeurl.ts
Last active March 5, 2020 17:32
Define your React Router URLs as objects that can be used both in your router and also to generate URL strings.
import { generatePath } from 'react-router';
// ## Route URL
export default class RouteUrl<P extends { [K in keyof P]?: string }> {
constructor(public routePath: string) {}
asPath(params: { [K in keyof P]: string | number | boolean }) {
return generatePath(this.routePath, params);
}