Skip to content

Instantly share code, notes, and snippets.

@shiftyp
Last active August 22, 2020 17:01
Show Gist options
  • Save shiftyp/1a4fa5e28343b2aedee7a93c355b41c1 to your computer and use it in GitHub Desktop.
Save shiftyp/1a4fa5e28343b2aedee7a93c355b41c1 to your computer and use it in GitHub Desktop.
objects 0.2.0 example
import React from 'react'
import { useStable, useWatch } from '@objects/hooks'
import { through, map, debounce } from '@objects/operators'
interface Search {
title: string
}
interface Data {
results: string[]
}
export const MovieSearch = () => {
// Creates a stable object reference
const [search] = useStable(() => ({
title: '',
}) as Search)
// Connects changes in the object's properties to component state updates
useWatch(search)()
// Connects changes in the object's title property to effects and computed state
const movies: string[] = useWatch(search).title(
through(
debounce(),
map((title: string) => (
fetch(`/api?q=${title}`)
.then(resp => resp.json() as Promise<Data>)
.then(data => data.results)
)),
),
[]
)
return (
<div>
<input
value={search.title}
onChange={(e) => {
// Mutate the object!
search.title = e.target.value
}}
/>
<ul>
{movies.length ? movies.map(movie => <li>{movie}</li>) : <li>No Results</li>}
</ul>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment