Last active
November 5, 2018 17:50
-
-
Save busypeoples/ab5efae6c78692417ccdd332ee9bfd40 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { render } from "react-dom"; | |
import Task from "data.task"; | |
import TaskComponent from "./TaskComponent"; | |
const users = [ | |
{ id: 1, name: "User A", points: 45 }, | |
{ id: 2, name: "User B", points: 22 }, | |
{ id: 3, name: "User C", points: 79 }, | |
{ id: 4, name: "User D", points: 54 } | |
]; | |
const fakeFetch = () => { | |
return new Promise((res, rej) => { | |
setTimeout(() => res({ users }), 2000); | |
}); | |
}; | |
const UserTask = new Task((rej, res) => { | |
fakeFetch() | |
.then(res) | |
.catch(rej); | |
}); | |
const UserComponent = ({ id, name, points }) => ( | |
<li> | |
{id} - {name} - points: {points} | |
</li> | |
); | |
const App = () => ( | |
<TaskComponent | |
render={{ | |
notAsked: () => <div>Nothing Loaded</div>, | |
loading: () => <div>Loading...</div>, | |
error: error => <div>Something went wrong: {error}</div>, | |
success: ({ users }) => ( | |
<ul>{users.map(user => <UserComponent key={user.id} {...user} />)}</ul> | |
) | |
}} | |
task={UserTask} | |
/> | |
); | |
render(<App />, document.getElementById("root")); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
const NOTASKED = "NOTASKED"; | |
const LOADING = "LOADING"; | |
const SUCCESS = "SUCCESS"; | |
const ERROR = "ERROR"; | |
const cata = (type, data = null) => o => o[type](data); | |
const Data = { | |
notAsked: () => ({ type: NOTASKED, cata: cata(NOTASKED) }), | |
loading: () => ({ type: LOADING, cata: cata(LOADING) }), | |
error: error => ({ type: ERROR, error, cata: cata(ERROR, error) }), | |
success: data => ({ type: SUCCESS, data, cata: cata(SUCCESS, data) }) | |
}; | |
class TaskComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = Data.notAsked(); | |
} | |
componentDidMount() { | |
this.setState(Data.loading()); | |
this.props.task.fork( | |
error => this.setState(Data.error(error)), | |
data => this.setState(Data.success(data)) | |
); | |
} | |
render() { | |
const { render } = this.props; | |
return this.state.cata({ | |
NOTASKED: render.notAsked, | |
LOADING: render.loading, | |
ERROR: render.error, | |
SUCCESS: render.success | |
}); | |
} | |
} | |
export default TaskComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment