Simple code with ts-elmish: a brass tacks explanation

// main.tsx
import * as React from ‘react’
import { render } from ‘react-dom’
import { createElmishComponent } from ‘@ts-elmish/react’// Our callback needs the 'dispatch' function to send a message.
// We'll make our sender functions take it and yield a packaged
// up function that actually sends the message.
//
// Initially i was expecting callbacks to be wrapped in this kind
// of function automatically, but they aren't.
function sender(dispatch,f) {
return (e) => dispatch(f(e));
}
// Make a component that does something.
// note: although you control the state (left side of the
// init "tuple"), a "dispatch" function is added to it by the
// framework, thus the state type is Record<String,any>
const App = createElmishComponent({
init: () => [{count: 0}, []],
update: (state, action) => {
// Make a new state without mutation using the message content
// action is the list given below.
return [{
count: state.count + action[0].add
}, []];
},
view: state => {
return <div>
<h1>Hi there</h1>
<!-- View contains a function sending a message.
-- The function given to sender can use the event
-- argument if it needs.
-- Importantly, message is expected to be enlisted.
-->
<button onClick={sender(state.dispatch, () => [{add:1}])}>
{state.count}
</button>
</div>;
}
});
// And use the component!
render(<App />, document.getElementById(‘app’));

An old programmer learning new tricks.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Building custom Docker images from cypress/included

How I got a 100% Lighthouse score with my React app

How Babel helped to save 710kb from a production bundle and how it’s so much more than esnext…

Separating frontend and backend routes in Laravel

Design a simple Login & Signup form with validation using HTML, CSS & JavaScript

Game Development with Angular: How to Build Your Own Tetris Clone

Bridging The Gap With Google App Script

Event Loop, hoisting, rest vs spread operator, data types and Cross Browser Testing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
art yerkes

art yerkes

An old programmer learning new tricks.

More from Medium

next-export-i18n v1.3.0: respecing the user’s default language

Performance boost for Remirror positioners

ReactJs and Webpack Bundle Optimizations

Using Params and Filter to Render a Page with Specific Item From List