Skip to content

Instantly share code, notes, and snippets.

@wildseansy
Last active October 24, 2021 17:33
Show Gist options
  • Save wildseansy/5aeab76ea0cfa456d0ed6268e011c3b0 to your computer and use it in GitHub Desktop.
Save wildseansy/5aeab76ea0cfa456d0ed6268e011c3b0 to your computer and use it in GitHub Desktop.
[Redux Migration Example] Step 1
//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;
//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