Last active
October 24, 2021 17:33
-
-
Save wildseansy/5aeab76ea0cfa456d0ed6268e011c3b0 to your computer and use it in GitHub Desktop.
[Redux Migration Example] Step 1
This file contains 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
//UserReducer | |
type User = { | |
id: string; | |
name: string; | |
}; | |
type UserReducerState = Record<string, User>; | |
const updateUser = (user: User, state: UserReducerState) => { | |
state[user.id] = {...user}; | |
return {...state}; | |
} | |
const deleteUser = (user: User, state: UserReducerState) => { | |
delete state[user.id]; | |
return {...state}; | |
} | |
type UserAction = { | |
type: "UPDATE_USER" | "DELETE_USER", | |
payload: User | |
}; | |
const UserReducer = (state: UserReducerState, action: UserAction) => { | |
switch (action.type) { | |
case "UPDATE_USER": | |
return updateUser(action.payload, state) | |
case "DELETE_USER": | |
return deleteUser(action.payload, state) | |
default: | |
return state; | |
} | |
}; | |
// Stored under "users" key in root reducer. | |
export default UserReducer; |
This file contains 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
//UsersList | |
import * as React from "react"; | |
import { connect } from "react-redux"; | |
import { User } from "app/redux/user-reducer"; | |
// UserItem represents a user item in the list | |
import UserItem from "app/components/UserItem"; | |
type Props = { | |
users: User[]; | |
onUpdate: (user: User) => void; | |
onDelete: (user: User) => void; | |
}; | |
class UsersList extends React.Component<Props> { | |
render() { | |
const { users } = this.props; | |
return users.map((user: User) => { | |
return <UserItem key={user.id} onTapDelete={this.props.onDelete} onUpdate={this.props.onUpdate} />; | |
}); | |
} | |
} | |
const getUsers = (state) => Object.values(state.users); | |
const mapStateToProps = (state) => { | |
return { | |
users: getUsers(state), | |
}; | |
}; | |
const mapDispatchToProps = (dispatch) => ({ | |
onUpdate: (user: User) => dispatch({ type: "UPDATE_USER", payload: user }), | |
onDelete: (user: User) => dispatch({ type: "DELETE_USER", payload: user }), | |
}); | |
export default connect(mapStateToProps, mapDispatchToProps)(UsersList); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment