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

Part 1: simplr-forms — declarative forms for React. Why are we doing this?

Practical React: Understanding Async with Redux Sagas. (Pt. 1)

Important information about JavaScript.

Fun with Stamps. Episode 5. Composition design pattern

How to Learn React #5 — Quick Introduction to Component State

BugPoc LFI challenge Walkthrough

How to fix error laravel log could not be opened in append mode.

JavaScript Coding Interview Questions and Solutions

javascript coding interview

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

Patreon_clone with React

6 Techs to become most wanted fullstack developer + amazing courses

Local Line 2.0 Front End

What is React-Redux and Why it is used?