Maybe functor-React.js with Folktale.js
This article wants to intergrate the Folktale.js Maybe type in a React.js application
We are going to use the Maybe type from a Functional Library called Folktale.js. Folktale is probably the 3rd most popular Functional library (after Rambda and Senctuary.js)
If you are not familiar with the maybe functor read the previous article :
Folktale provides a Maybe Type with the two Cases named Just
and Nothing
. Other that that we have a map
method and a pattern matching method called matchWith
Maybe.matchWith({
Just: ({ value }) => _,
Nothing: () => _
});
The core example use case, upon which we are going to build the various ideas in this course is a simple retrieval of a Client
from a database Repository
that matches a specific Id.
The mock repository with an in-memory storage of the Clients in an Array might look like this:
var Repository = ({
getById: id =>
[new Client(1, "jim"),
new Client(2, "jane")]
.filter(client => client.id == id) //return an array [Client]. Could be an Empty []
});
If we use the Maybe Folktale Library we can create a ClientService
:
let ClientService = ({
getClientNameById: id =>
Repository.getById(id)
.map(Client.name)
.matchWith({
Just: ({ value }) => `Found: ${value}`,
Nothing: () => 'Nothing was found'
})
});
We can now integrate this simple ClientService
in a React.js application.
This is not a React.js article, so we are not going to expand on the React concepts. You can try to run the Application bellow. When you type any integer value into the text input, react calls the ClientService
retrieves the client name and display it into a <div>
.
import React from 'react';
import { ClientService } from "./ClientService.js"
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { id: '' };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
clientName: ClientService.getClientNameById(event.target.value),
id: event.target.value
});
}
render() {
return (
<form >
<label>
Id:
<input type="text" value={this.state.id} onChange={this.handleChange} />
</label>
<div> {this.state.clientName} </div>
</form>
);
}
}
This React app is very simple. The core of the app is in the app.js file. Inside the render()
method you can find the html snippet that the component renders:
<form>
<label>
Name:
<input type="text" value={this.state.id} onChange={this.handleChange} />
</label>
<div> {this.state.clientName} </div>
</form>
The mechanics are simple :
- The
<input type="text">
has an onChange event attached, so when we type in the box the Component calls thehandleChange
function - The
handleChange
in turn updates the clientName property of the state :
this.setState({
clientName: ClientService.getClientNameById(event.target.value),
id: event.target.value
});
3. the clientName
property of the state is bind to the div, which is updated in real time
<div> {this.state.clientName} </div>