Skip to content

Instantly share code, notes, and snippets.

@guillaumewuip
guillaumewuip / middleware.js
Created November 12, 2020 06:56
State and Store in frontend codebases - Redux example - middleware
import { fetchUsers, createUser } from "./fake-fetch";
import {
fetchUsersSucceeded,
fetchUsersFailed,
createUserFailed,
createUserSucceeded
} from "./actionCreators";
export const middleware = ({ dispatch, getState }) => (next) => (action) => {
@guillaumewuip
guillaumewuip / reducer.js
Created November 12, 2020 06:55
State and Store in frontend codebases - Redux example - reducer
const initialState = { loading: true, users: [], error: undefined };
export function reducer(state = initialState, action) {
console.log({ type: action.type, action });
switch (action.type) {
case "FETCH_USERS_SUCCEEDED":
return {
...state,
loading: false,
users: action.payload.users.filter(
@guillaumewuip
guillaumewuip / actionCreators.js
Last active November 12, 2020 06:58
State and Store in frontend codebases - Redux example - actionCreators
export const fetchUsers = () => ({
type: "FETCH_USERS"
});
export const fetchUsersFailed = () => ({
type: "FETCH_USERS_FAILED"
});
export const fetchUsersSucceeded = (users) => ({
type: "FETCH_USERS_SUCCEEDED",
payload: {
users
// text :: (text: Text) => string
export const text = MessageUnion.Text.lensFromProp(‘text’).get;
// updateText :: (content: string) => (text: Text) => Text
export const updateText = MessageUnion.Text.lensFromProp(‘text’).set;
export function addSignature(signature: string) {
return (text: Text) => {
const $text = MessageUnion.Text.iso.unwrap(text); // get private type
const $newText = {
…$text,
text: `${$message.text} - ${signature}`,
};
return MessageUnion.Text.iso.wrap($newText); // get opaque type
};
}
import * as Message from ‘../path/to/message.ts’;
const message: Message = Message.createText({ text: ‘hello world’ });
if (Message.isText(message)) {
return <p>This is a text</p>;
} else {
return <p>This is an image</p>;
}
export const isText = MessageUnion.is.Text;
export const isImage = MessageUnion.is.Image;
export const fold = MessageUnion.fold;
export function createEmptyText() {
return MessageUnion.of.Text({ text: ‘’ }); // you must pass a $Text here
}
export const createText = MessageUnion.of.Text;
export const createImage = MessageUnion.of.Image;
export type Text = ReturnType<typeof MessageUnion.of.Text>;
export type Image = ReturnType<typeof MessageUnion.of.Image>;
type $Text = {
text: string;
};
type $Image = {
url: string;
description: string;
};
const MessageUnion = Union.of({