Skip to content

Instantly share code, notes, and snippets.

View gaperton's full-sized avatar

Vlad Balin gaperton

View GitHub Profile
function useIO( fun, condition = [] ) {
// Counter of open I/O requests. If it's 0, I/O is completed.
// Counter is needed to handle the situation when the next request
// is issued before the previous one was completed.
const $isReady = useSafeLink( null );
useEffect(()=>{
// function in set instead of value to avoid race conditions with counter increment.
$isReady.set( x => ( x || 0 ) + 1 );
function useThrottle( fun, timeout, changes = [] ){
// Create the mutable local ref to store timer.
const timer = useRef( null );
function cancel(){
if( timer.current ){
clearTimeout( timer.current );
timer.current = null;
}
}
export const DelayedInput = ({ $value, timeout = 1000, ...props }) => {
const $inputValue = useBoundLink( $value )
.onChange(
useThrottle(
x => $value.set( x ),
timeout,
[ $value.value ]
)
);
export const DelayedInput = ({ $value, timeout = 1000, …props }) => {
 const $inputValue = useBoundLink( $value );
 // TODO: How to sync the state back?
 return <input {…$inputValue.props} {…props}/>;
}
export const EditUser = ({ $selected, close }) => {
const $filter = useLink('');
return (
<>
<DelayedInput autoFocus
$value={ $filter }
placeholder="Start typing..."
onBlur={ close } />
@gaperton
gaperton / pickuser.jsx
Last active May 17, 2019 04:36
Show user
const userToString = x => x.name + ' <' + x.email + '>';
const PickUser = ({ user }) => (
<div>
  <input value={userToString(user)}/>
</div>
)
@gaperton
gaperton / pickuser2.jsx
Last active May 17, 2019 04:37
PuckUser Component
function useLink( init ){
const [ value, set ] = useState( init );
// It can be a class with useful methods, like this one:
// https://github.com/VoliJS/NestedLink/blob/master/valuelink/src/link.ts
// But we just use the plain object here to illustrate an idea.
return { value, set };
}
const PickUser = ({ $selected /* link to some upper component state */ }) => {
// Declare the local component's state as a link.
import React from 'react';
import { useLink } from 'valuelink'
function Example() {
const users = useLink([]);
return (
<div>
{ users.map( ( user, i ) => (
<div key={i}>
// Minimal working example demonstrating the two-way data binding with React Hook.
import { useLink } from 'valuelink'
import * as React from 'react'
// We don't want to deal with error markup in every input, do we?
const Input = ({ link, ...props }) => {
return (
<div>
<input {...link.props} {...props} />
<span>{ link.error || '' }</span>