Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
lejonmanen / index.js
Last active October 29, 2023 16:38
Using Node.js async readline
import { getQuestion } from './readline.js'
const [question, close] = getQuestion()
let input = await question('Please input a number')
console.log(`The number is: ${input}.`)
close()
@lejonmanen
lejonmanen / ContextDemo.jsx
Created April 11, 2022 09:43
React Context demo using hooks
import { createContext, useState, useContext } from 'react'
// Create the context in a separate file. Import it to every component that needs it.
const CounterContext = createContext(0)
const ContextDemo = () => {
const [count, setCount] = useState(2)
const contextValue = { count, setCount }
@lejonmanen
lejonmanen / MediaDevice.jsx
Created November 11, 2021 20:40
Use MediaDevices to display video stream from webcam in a React component.
import { useRef } from 'react'
const MediaDevice = () => {
const videoRef = useRef(null)
const handleVideoOn = () => assignStream(videoRef.current)
const handleVideoOff = () => videoRef.current.srcObject = null
return (
<div>
@lejonmanen
lejonmanen / useCancellableAjax.js
Last active March 20, 2024 21:47
React hook for sending fetch requests and cancelling them safely.
import { useEffect, useRef } from 'react'
/*
Safely send and cancel one AJAX request at the time. If you need to send multiple requests at the same time, call this hook several times.
Usage:
const [cancelRef, doAjax] = useCancellableAjax()
Fetch data. Tip: use a setState function as callback.
doAjax(url, fetchOptions, dataCallback)
@lejonmanen
lejonmanen / script.js
Last active December 20, 2021 15:46
Minimal service worker for use when developing a PWA
// Copy and paste this code into your main script file
// The purpose is to register the service worker
// The browser will load sw.js for us if you do this
if ('serviceWorker' in navigator) {
// Assumes your service worker has file name "sw.js"
navigator.serviceWorker.register('sw.js')
.then(reg => {
console.log('Registration succeeded. Scope is ' + reg.scope);
});