Skip to content

Instantly share code, notes, and snippets.

@corlaez
Created July 23, 2019 23:16
Show Gist options
  • Save corlaez/e36de88351e215772658211f62503816 to your computer and use it in GitHub Desktop.
Save corlaez/e36de88351e215772658211f62503816 to your computer and use it in GitHub Desktop.
Overmind snapshots of different files of a project. Just to get a feel of it.
/* state.ts
* Here we define the initial state of the application.
* I have ommited the types for Newspapers, Table and State for brevity.
*/
export const state: State = {
table: {
selected: null,
newspapers: [],
},
}
/* effects.ts
* Api calls like this won't work in node so they are a great candidate to
* write as an effects because overmind allows you to mock them easily for tests.
*/
export const fetchArticle = async (articleId: number): Promise<any> => {
const url = '/api/article.js?' +
'id=' + articleId
try {
const response = await fetch(url)
const array = (await response.json()) as any
return array[0].text
} catch (e) {
console.error(e)
return null
}
}
/* actions.ts
* Where your business logic lives and the only place where state changes.
* This particular case will set expanded to true, but if article.text is null will also pull the text async.
*/
export const expandArticle: AsyncAction<number> = async ({state, effects}, articleId) => {
const article = state.table.newspapers.find(
(article : Newspaper) => article.id === articleId
)
if(article) {
if(article.text == null) {
article.text = await effects.fetchArticle(articleId)
}
article.expanded = true
}
}
// api.ts Where the app is configured. Namespace is supported but it is not depicted here
import { createConnect, createHook, IConnect } from 'overmind-react'
import { IConfig } from 'overmind'
import { state } from './state'
import * as actions from './actions'
import * as effects from './effects'
import onInitialize from './on-initialize'
export const config = {
onInitialize,
state,
actions,
effects,
}
// For explicit typing check the Typescript guide
declare module 'overmind' {
interface Config extends IConfig<typeof config> {}
}
// hook
export const useOvermind = createHook<typeof config>()
// hoc
export interface Connect extends IConnect<typeof config> {}
export const connect = createConnect<typeof config>()
// react utils, needs refinement.
import { ChangeEvent } from 'react'
type Action = (v: string) => void
export const setInput = (action: Action) =>
(e: ChangeEvent<HTMLInputElement>) => action(e.target.value)
export const setSelect = (action: Action) =>
(e: ChangeEvent<HTMLSelectElement>) => action(e.target.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment