Skip to content

Instantly share code, notes, and snippets.

@wildseansy
Last active October 29, 2021 00:24
Show Gist options
  • Save wildseansy/2b81b40989453d33e731be13cef81a19 to your computer and use it in GitHub Desktop.
Save wildseansy/2b81b40989453d33e731be13cef81a19 to your computer and use it in GitHub Desktop.
[Redux Migration Example] Step 3
// User useUserStore hook, and context creation
import * as React from "react";
type User = {
id: string;
name: string;
}
type UserStore = {
users: User[];
updateUser: (user: User) => void;
deleteUser: (user: User) => void;
}
const INITIAL_USERS_STATE: UserStore = {
users: [];
deleteUser: () => {
//Intentionally blank - set in UserStoreProvider below
};
updateUser: () => {
//Intentionally blank - set in UserStoreProvider below
};
}
const UserStoreContext = React.createContext<UserStore>(INITIAL_USERS_STATE)
// Our provider, to include near the top of the application, so most components may access its state.
export const UserStoreProvider: React.FC = ({ children }) => {
const [users, setUsers] = React.useState([]);
React.useEffect(() => {
fetchUsersFromAPI().then((serverUsers: User[]) => {
setUsers(users)
})
}, [setUsers]);
const updateUser = React.useCallback(async (user) => {
// Perhaps you update the server:
// await updateServerUser(user);
setUsers(
users.map((item) => {
if (item.id === user.id) {
return {...user};
}
return item;
})
);
}, [setUsers, users]);
const deleteUser = React.useCallback(async (user) => {
// Perhaps you update the server:
// await deleteServerUser(user);
setUsers(
users.filter((item) => {
return item.id !== user.id;
})
);
}, [setUsers, users]);
const userStore = React.useMemo(() => {
return { deleteUser, updateUser, users }
}, [deleteUser, updateUser, users]);
return (
<UserStoreContext.Provider value={userStore}>
{children}
</UserStoreContext.Provider>
);
}
// Our hook, which just exposes the shared context to any components under 'UserStoreProvider'
export const useUserStore = () => React.useContext(UserStoreContext)
// UsersList without redux
import * as React from "react";
import { useUserStore } from "app/hooks/user-hooks"
// UserItem represents a user item in the list
import UserItem from "app/components/UserItem";
const UsersList: React.FC = () => {
const { users, updateUser, deleteUser } = useUserStore();
return users.map((user: User) => {
return <UserItem key={user.id} onTapDelete={deleteUser} onUpdate={updateUser} />;
});
}
export default UsersList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment