Last active
April 10, 2018 05:31
-
-
Save agoldis/49f73c65d545f943e104038549008d22 to your computer and use it in GitHub Desktop.
redux blog
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
/* | |
index.js | |
*/ | |
import React from "react"; | |
import { render } from "react-dom"; | |
import { Provider } from "react-redux"; | |
import { createStore } from "redux"; | |
import Header from "./Header"; | |
import UserTasks from "./UserTasks"; | |
const initialState = { | |
users: [{ id: "user01", name: "John" }, { id: "user02", name: "Bob" }], | |
tasks: [ | |
{ id: "task01", title: "Wash car", assignee: "user01" }, | |
{ id: "task02", title: "Watch tutorial", assignee: "user01" }, | |
{ id: "task03", title: "Do Homework", assignee: "user02" } | |
] | |
} | |
const store = createStore((state = initialState) => state, initialState); | |
const Root = () => ( | |
<Provider store={store}> | |
<Header /> | |
<UserTasks /> | |
</Provider> | |
); | |
render(<Root />, document.getElementById("root")); | |
/* | |
UserTasks.js | |
*/ | |
import React from "react"; | |
import { connect } from "react-redux"; | |
const mapStateToProps = ({ users = [], tasks = [] } = {}) => ({ | |
tasksByUsers: users.map( | |
user => Object.assign( | |
user, | |
{ tasks: tasks.filter(t => t.assignee === user.id) }) // modifying state!! | |
) | |
}); | |
class UserTasks extends React.Component { | |
render() { | |
const { tasksByUsers } = this.props; | |
return <div> | |
{JSON.stringify(tasksByUsers)} | |
</div> | |
} | |
} | |
export default connect(mapStateToProps)(UserTasks) | |
/* | |
Header.js | |
*/ | |
import React from "react"; | |
import { connect } from "react-redux"; | |
const mapStateToProps = ({ users = [], tasks = [] } = {}) => ({ | |
tasksCountByUsers: users.map( | |
user => Object.assign( | |
user, | |
{ tasksCount: tasks.filter(t => t.assignee === user.id).length }) // modifying state!! | |
) | |
}); | |
class Header extends React.Component { | |
render() { | |
const { tasksCountByUsers } = this.props; | |
return <div> | |
{JSON.stringify(tasksCountByUsers)} | |
</div> | |
} | |
} | |
export default connect(mapStateToProps)(Header) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment