Skip to content

Instantly share code, notes, and snippets.

View gianmarcotoso's full-sized avatar

Gian Marco Toso gianmarcotoso

View GitHub Profile
@gianmarcotoso
gianmarcotoso / use-form.hook.js
Last active February 19, 2019 10:02
A `useForm` hook to handle forms within a React component using the hooks API
import { useState } from 'react'
export const useForm = (initialValue, middlewareFn) => {
const [data, setData] = useState(initialValue);
const middleware =
typeof middlewareFn === "function" ? middlewareFn : data => data;
/*
- onChange(event)
uses the event target's `name` and `value` (or `checked` if the type of the target is "checkbox")
@gianmarcotoso
gianmarcotoso / use-redux.hook.js
Created December 13, 2018 14:41
A simple `useRedux` hook to "connect" components to redux using react hooks
import { useState, useContext, useEffect } from 'react'
import { StoreContext } from '../contexts/store.context'
export const useRedux = (selector = state => state, mapDispatch = {}) => {
const store = useContext(StoreContext)
if (!store) {
throw new Error(
`Store not found. Wrap your application within a StoreProvider and pass it the appropriate store prop.`
)
}
@gianmarcotoso
gianmarcotoso / react-redux-context.tsx
Last active April 9, 2018 09:50
Connect React to Redux with Context API
import * as React from 'react'
import { Store, Unsubscribe, Dispatch } from 'redux'
const stateContext = React.createContext()
const { Provider, Consumer } = stateContext
export interface StateProviderProps<T> {
store: Store<T>
}
@gianmarcotoso
gianmarcotoso / search.js
Created June 13, 2016 15:49
A search function to use with Dexie.js to search an IndexedDB table using an object of where clauses
let search = function(db, tableName, query) {
let table = db.table(tableName)
let clause = Object.keys(query).reduce( (r, n) => {
if (typeof query[n] === "undefined" || query[n] === null) return r;
let where = !r ? table.where(n) : r.or(n)
if (query[n] && query[n].constructor === String) {
return where.startsWith(query[n])
@gianmarcotoso
gianmarcotoso / Sort.jsx
Last active June 18, 2017 15:34
React Sort HoC
import React from 'react';
import { Component } from 'react';
let Sort = Sortable => class extends Component {
constructor(props) {
super(props);
this.state = {
items: []
}
@gianmarcotoso
gianmarcotoso / Filter.jsx
Last active March 10, 2016 16:30
React Filter HoC
import React from 'react';
import { Component } from 'react';
let Filter = Filterable => class extends Component {
constructor(props) {
super(props);
this.state = {
items: props.items
};