chore: create helper function for interacting with apollo cache

This commit is contained in:
Jordan Knott 2020-06-23 16:55:17 -05:00
parent 57382de9d0
commit a589fbe399
7 changed files with 258 additions and 307 deletions

View File

@ -137,11 +137,11 @@ const ProjectFinder = () => {
return ( return (
<> <>
{projectTeams.map(team => ( {projectTeams.map(team => (
<TeamContainer> <TeamContainer key={team.id}>
<TeamTitle>{team.name}</TeamTitle> <TeamTitle>{team.name}</TeamTitle>
<TeamProjects> <TeamProjects>
{team.projects.map((project, idx) => ( {team.projects.map((project, idx) => (
<TeamProjectContainer> <TeamProjectContainer key={project.id}>
<TeamProjectLink to={`/projects/${project.id}`}> <TeamProjectLink to={`/projects/${project.id}`}>
<TeamProjectBackground color={colors[idx % 5]} /> <TeamProjectBackground color={colors[idx % 5]} />
<TeamProjectAvatar color={colors[idx % 5]} /> <TeamProjectAvatar color={colors[idx % 5]} />

View File

@ -18,6 +18,7 @@ import {
useUpdateTaskChecklistItemNameMutation, useUpdateTaskChecklistItemNameMutation,
useCreateTaskChecklistItemMutation, useCreateTaskChecklistItemMutation,
FindTaskDocument, FindTaskDocument,
FindTaskQuery,
} from 'shared/generated/graphql'; } from 'shared/generated/graphql';
import UserIDContext from 'App/context'; import UserIDContext from 'App/context';
import MiniProfile from 'shared/components/MiniProfile'; import MiniProfile from 'shared/components/MiniProfile';
@ -27,9 +28,10 @@ import styled from 'styled-components';
import Button from 'shared/components/Button'; import Button from 'shared/components/Button';
import Input from 'shared/components/Input'; import Input from 'shared/components/Input';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import updateApolloCache from 'shared/utils/cache';
const calculateChecklistBadge = (draftState: any) => { const calculateChecklistBadge = (checklists: Array<TaskChecklist>) => {
const total = draftState.checklists.reduce((prev: any, next: any) => { const total = checklists.reduce((prev: any, next: any) => {
return ( return (
prev + prev +
next.items.reduce((innerPrev: any, _item: any) => { next.items.reduce((innerPrev: any, _item: any) => {
@ -37,7 +39,7 @@ const calculateChecklistBadge = (draftState: any) => {
}, 0) }, 0)
); );
}, 0); }, 0);
const complete = draftState.checklists.reduce( const complete = checklists.reduce(
(prev: any, next: any) => (prev: any, next: any) =>
prev + prev +
next.items.reduce((innerPrev: any, item: any) => { next.items.reduce((innerPrev: any, item: any) => {
@ -131,171 +133,104 @@ const Details: React.FC<DetailsProps> = ({
const [memberPopupData, setMemberPopupData] = useState(initialMemberPopupState); const [memberPopupData, setMemberPopupData] = useState(initialMemberPopupState);
const [setTaskChecklistItemComplete] = useSetTaskChecklistItemCompleteMutation({ const [setTaskChecklistItemComplete] = useSetTaskChecklistItemCompleteMutation({
update: client => { update: client => {
const cacheData: any = client.readQuery({ updateApolloCache<FindTaskQuery>(
query: FindTaskDocument, client,
variables: { taskID }, FindTaskDocument,
}); cache =>
const newData = produce(cacheData.findTask, (draftState: any) => { produce(cache, draftCache => {
const { complete, total } = calculateChecklistBadge(draftState); const { complete, total } = calculateChecklistBadge(draftCache.findTask.checklists);
if (!draftState.badges) { draftCache.findTask.badges.checklist = {
draftState.badges = { __typename: 'ChecklistBadge',
checklist: {}, complete,
}; total,
} };
draftState.badges.checklist = { }),
__typename: 'ChecklistBadge', { taskID },
complete, );
total,
};
});
client.writeQuery({
query: FindTaskDocument,
variables: { taskID },
data: {
findTask: newData,
},
});
}, },
}); });
const [deleteTaskChecklist] = useDeleteTaskChecklistMutation({ const [deleteTaskChecklist] = useDeleteTaskChecklistMutation({
update: (client, deleteData) => { update: (client, deleteData) => {
const cacheData: any = client.readQuery({ updateApolloCache<FindTaskQuery>(
query: FindTaskDocument, client,
variables: { taskID }, FindTaskDocument,
}); cache =>
console.log(deleteData); produce(cache, draftCache => {
const { checklists } = cache.findTask;
const newData = produce(cacheData.findTask, (draftState: any) => { const item = deleteData.deleteTaskChecklist;
draftState.checklists = cacheData.findTask.checklists.filter( draftCache.findTask.checklists = checklists.filter(c => c.id !== item.taskChecklist.id);
(checklist: any) => checklist.id !== deleteData.data.deleteTaskChecklist.taskChecklist.id, const { complete, total } = calculateChecklistBadge(draftCache.findTask.checklists);
); draftCache.findTask.badges.checklist = {
const { complete, total } = calculateChecklistBadge(draftState); __typename: 'ChecklistBadge',
if (!draftState.badges) { complete,
draftState.badges = { total,
checklist: {}, };
}; if (complete === 0 && total === 0) {
} draftCache.findTask.badges.checklist = null;
draftState.badges.checklist = { }
__typename: 'ChecklistBadge', }),
complete, { taskID },
total, );
};
if (complete === 0 && total === 0) {
draftState.badges.checklist = null;
}
});
client.writeQuery({
query: FindTaskDocument,
variables: { taskID },
data: {
findTask: newData,
},
});
}, },
}); });
const [updateTaskChecklistItemName] = useUpdateTaskChecklistItemNameMutation(); const [updateTaskChecklistItemName] = useUpdateTaskChecklistItemNameMutation();
const [createTaskChecklist] = useCreateTaskChecklistMutation({ const [createTaskChecklist] = useCreateTaskChecklistMutation({
update: (client, createData) => { update: (client, createData) => {
const cacheData: any = client.readQuery({ updateApolloCache<FindTaskQuery>(
query: FindTaskDocument, client,
variables: { taskID }, FindTaskDocument,
}); cache =>
console.log(createData); produce(cache, draftCache => {
const item = createData.data.createTaskChecklist;
const newData = { draftCache.findTask.checklists.push({ ...item });
findTask: { }),
...cacheData.findTask, { taskID },
checklists: [...cacheData.findTask.checklists, { ...createData.data.createTaskChecklist }], );
},
};
client.writeQuery({
query: FindTaskDocument,
variables: { taskID },
data: newData,
});
}, },
}); });
const [updateTaskChecklistName] = useUpdateTaskChecklistNameMutation(); const [updateTaskChecklistName] = useUpdateTaskChecklistNameMutation();
const [deleteTaskChecklistItem] = useDeleteTaskChecklistItemMutation({ const [deleteTaskChecklistItem] = useDeleteTaskChecklistItemMutation({
update: (client, deleteData) => { update: (client, deleteData) => {
const cacheData: any = client.readQuery({ updateApolloCache<FindTaskQuery>(
query: FindTaskDocument, client,
variables: { taskID }, FindTaskDocument,
}); cache =>
console.log(deleteData); produce(cache, draftCache => {
const newData = produce(cacheData.findTask, (draftState: any) => { const item = deleteData.data.deleteTaskChecklistItem.taskChecklistItem;
const idx = draftState.checklists.findIndex( draftCache.findTask.checklists = cache.findTask.checklists.filter(c => item.id !== c.id);
(checklist: TaskChecklist) => const { complete, total } = calculateChecklistBadge(draftCache.findTask.checklists);
checklist.id === deleteData.data.deleteTaskChecklistItem.taskChecklistItem.taskChecklistID, draftCache.findTask.badges.checklist = {
); __typename: 'ChecklistBadge',
console.log(`idx ${idx}`); complete,
if (idx !== -1) { total,
draftState.checklists[idx].items = cacheData.findTask.checklists[idx].items.filter(
(item: any) => item.id !== deleteData.data.deleteTaskChecklistItem.taskChecklistItem.id,
);
const { complete, total } = calculateChecklistBadge(draftState);
if (!draftState.badges) {
draftState.badges = {
checklist: {},
}; };
} }),
draftState.badges.checklist = { { taskID },
__typename: 'ChecklistBadge', );
complete,
total,
};
}
});
client.writeQuery({
query: FindTaskDocument,
variables: { taskID },
data: {
findTask: newData,
},
});
}, },
}); });
const [createTaskChecklistItem] = useCreateTaskChecklistItemMutation({ const [createTaskChecklistItem] = useCreateTaskChecklistItemMutation({
update: (client, newTaskItem) => { update: (client, newTaskItem) => {
const cacheData: any = client.readQuery({ updateApolloCache<FindTaskQuery>(
query: FindTaskDocument, client,
variables: { taskID }, FindTaskDocument,
}); cache =>
console.log(cacheData); produce(cache, draftCache => {
console.log(newTaskItem); const item = newTaskItem.data.createTaskChecklistItem;
const newData = produce(cacheData.findTask, (draftState: any) => { const { checklists } = cache.findTask;
const idx = draftState.checklists.findIndex( const idx = checklists.findIndex(c => c.id === item.taskChecklistID);
(checklist: TaskChecklist) => checklist.id === newTaskItem.data.createTaskChecklistItem.taskChecklistID, if (idx !== -1) {
); draftCache.findTask.checklists[idx].items.push({ ...item });
if (idx !== -1) { const { complete, total } = calculateChecklistBadge(draftCache.findTask.checklists);
draftState.checklists[idx].items = [ draftCache.findTask.badges.checklist = {
...cacheData.findTask.checklists[idx].items, __typename: 'ChecklistBadge',
{ ...newTaskItem.data.createTaskChecklistItem }, complete,
]; total,
console.log(draftState.checklists.map((item: any) => item.items)); };
const { complete, total } = calculateChecklistBadge(draftState); }
if (!draftState.badges) { }),
draftState.badges = { { taskID },
checklist: {}, );
};
}
draftState.badges.checklist = {
__typename: 'ChecklistBadge',
complete,
total,
};
console.log(draftState.badges.checklist);
}
});
console.log(newData);
client.writeQuery({
query: FindTaskDocument,
variables: { taskID },
data: {
findTask: newData,
},
});
}, },
}); });
const { loading, data, refetch } = useFindTaskQuery({ variables: { taskID } }); const { loading, data, refetch } = useFindTaskQuery({ variables: { taskID } });

View File

@ -1,8 +1,9 @@
// LOC830
import React, { useState, useRef, useContext, useEffect } from 'react'; import React, { useState, useRef, useContext, useEffect } from 'react';
import { MENU_TYPES } from 'shared/components/TopNavbar'; import { MENU_TYPES } from 'shared/components/TopNavbar';
import updateApolloCache from 'shared/utils/cache';
import GlobalTopNavbar, { ProjectPopup } from 'App/TopNavbar'; import GlobalTopNavbar, { ProjectPopup } from 'App/TopNavbar';
import styled from 'styled-components/macro'; import styled from 'styled-components/macro';
import { DataProxy } from '@apollo/client';
import { Bolt, ToggleOn, Tags, CheckCircle, Sort, Filter } from 'shared/icons'; import { Bolt, ToggleOn, Tags, CheckCircle, Sort, Filter } from 'shared/icons';
import { usePopup, Popup } from 'shared/components/PopupMenu'; import { usePopup, Popup } from 'shared/components/PopupMenu';
import { useParams, Route, useRouteMatch, useHistory, RouteComponentProps } from 'react-router-dom'; import { useParams, Route, useRouteMatch, useHistory, RouteComponentProps } from 'react-router-dom';
@ -45,33 +46,9 @@ import produce from 'immer';
import MiniProfile from 'shared/components/MiniProfile'; import MiniProfile from 'shared/components/MiniProfile';
import Details from './Details'; import Details from './Details';
import { useApolloClient } from '@apollo/react-hooks'; import { useApolloClient } from '@apollo/react-hooks';
import { DocumentNode } from 'graphql';
import UserIDContext from 'App/context'; import UserIDContext from 'App/context';
import DueDateManager from 'shared/components/DueDateManager'; import DueDateManager from 'shared/components/DueDateManager';
type UpdateCacheFn<T> = (cache: T) => T;
function updateApolloCache<T>(client: DataProxy, document: DocumentNode, update: UpdateCacheFn<T>, variables?: object) {
let queryArgs: DataProxy.Query<any>;
if (variables) {
queryArgs = {
query: document,
variables,
};
} else {
queryArgs = {
query: document,
};
}
const cache: T | null = client.readQuery(queryArgs);
if (cache) {
const newCache = update(cache);
client.writeQuery({
...queryArgs,
data: newCache,
});
}
}
const getCacheData = (client: any, projectID: string) => { const getCacheData = (client: any, projectID: string) => {
const cacheData: FindProjectQuery = client.readQuery({ const cacheData: FindProjectQuery = client.readQuery({
query: FindProjectDocument, query: FindProjectDocument,
@ -140,25 +117,33 @@ const LabelManagerEditor: React.FC<LabelManagerEditorProps> = ({
const [currentLabel, setCurrentLabel] = useState(''); const [currentLabel, setCurrentLabel] = useState('');
const [createProjectLabel] = useCreateProjectLabelMutation({ const [createProjectLabel] = useCreateProjectLabelMutation({
update: (client, newLabelData) => { update: (client, newLabelData) => {
const cacheData = getCacheData(client, projectID); updateApolloCache<FindProjectQuery>(
const newData = { client,
...cacheData.findProject, FindProjectDocument,
labels: [...cacheData.findProject.labels, { ...newLabelData.data.createProjectLabel }], cache =>
}; produce(cache, draftCache => {
writeCacheData(client, projectID, cacheData, newData); draftCache.findProject.labels.push({ ...newLabelData.data.createProjectLabel });
}),
{
projectId: projectID,
},
);
}, },
}); });
const [updateProjectLabel] = useUpdateProjectLabelMutation(); const [updateProjectLabel] = useUpdateProjectLabelMutation();
const [deleteProjectLabel] = useDeleteProjectLabelMutation({ const [deleteProjectLabel] = useDeleteProjectLabelMutation({
update: (client, newLabelData) => { update: (client, newLabelData) => {
const cacheData = getCacheData(client, projectID); updateApolloCache<FindProjectQuery>(
const newData = { client,
...cacheData.findProject, FindProjectDocument,
labels: cacheData.findProject.labels.filter( cache =>
(label: any) => label.id !== newLabelData.data.deleteProjectLabel.id, produce(cache, draftCache => {
), draftCache.findProject.labels = cache.findProject.labels.filter(
}; label => label.id !== newLabelData.data.deleteProjectLabel.id,
writeCacheData(client, projectID, cacheData, newData); );
}),
{ projectId: projectID },
);
}, },
}); });
const labels = labelsRef.current ? labelsRef.current : []; const labels = labelsRef.current ? labelsRef.current : [];
@ -286,27 +271,29 @@ const Project = () => {
const [quickCardEditor, setQuickCardEditor] = useState(initialQuickCardEditorState); const [quickCardEditor, setQuickCardEditor] = useState(initialQuickCardEditorState);
const [updateTaskLocation] = useUpdateTaskLocationMutation({ const [updateTaskLocation] = useUpdateTaskLocationMutation({
update: (client, newTask) => { update: (client, newTask) => {
const cacheData = getCacheData(client, projectID); updateApolloCache<FindProjectQuery>(
console.log(cacheData); client,
console.log(newTask); FindProjectDocument,
cache =>
const newTaskGroups = produce(cacheData.findProject.taskGroups, (draftState: Array<TaskGroup>) => { produce(cache, draftCache => {
const { previousTaskGroupID, task } = newTask.data.updateTaskLocation; const { previousTaskGroupID, task } = newTask.data.updateTaskLocation;
if (previousTaskGroupID !== task.taskGroup.id) { if (previousTaskGroupID !== task.taskGroup.id) {
const oldTaskGroupIdx = draftState.findIndex((t: TaskGroup) => t.id === previousTaskGroupID); const { taskGroups } = cache.findProject;
const newTaskGroupIdx = draftState.findIndex((t: TaskGroup) => t.id === task.taskGroup.id); const oldTaskGroupIdx = taskGroups.findIndex((t: TaskGroup) => t.id === previousTaskGroupID);
if (oldTaskGroupIdx !== -1 && newTaskGroupIdx !== -1) { const newTaskGroupIdx = taskGroups.findIndex((t: TaskGroup) => t.id === task.taskGroup.id);
draftState[oldTaskGroupIdx].tasks = draftState[oldTaskGroupIdx].tasks.filter((t: Task) => t.id !== task.id); if (oldTaskGroupIdx !== -1 && newTaskGroupIdx !== -1) {
draftState[newTaskGroupIdx].tasks = [...draftState[newTaskGroupIdx].tasks, { ...task }]; draftCache.findProject.taskGroups[oldTaskGroupIdx].tasks = taskGroups[oldTaskGroupIdx].tasks.filter(
} (t: Task) => t.id !== task.id,
} );
}); draftCache.findProject.taskGroups[newTaskGroupIdx].tasks = [
...taskGroups[newTaskGroupIdx].tasks,
const newData = { { ...task },
...cacheData.findProject, ];
taskGroups: newTaskGroups, }
}; }
writeCacheData(client, projectID, cacheData, newData); }),
{ projectId: projectID },
);
}, },
}); });
const [updateTaskGroupLocation] = useUpdateTaskGroupLocationMutation({}); const [updateTaskGroupLocation] = useUpdateTaskGroupLocationMutation({});
@ -314,15 +301,17 @@ const Project = () => {
const [deleteTaskGroup] = useDeleteTaskGroupMutation({ const [deleteTaskGroup] = useDeleteTaskGroupMutation({
onCompleted: deletedTaskGroupData => {}, onCompleted: deletedTaskGroupData => {},
update: (client, deletedTaskGroupData) => { update: (client, deletedTaskGroupData) => {
const cacheData = getCacheData(client, projectID); updateApolloCache<FindProjectQuery>(
const newData = { client,
...cacheData.findProject, FindProjectDocument,
taskGroups: cacheData.findProject.taskGroups.filter( cache =>
(taskGroup: any) => taskGroup.id !== deletedTaskGroupData.data.deleteTaskGroup.taskGroup.id, produce(cache, draftCache => {
), draftCache.findProject.taskGroups = draftCache.findProject.taskGroups.filter(
}; (taskGroup: TaskGroup) => taskGroup.id !== deletedTaskGroupData.data.deleteTaskGroup.taskGroup.id,
);
writeCacheData(client, projectID, cacheData, newData); }),
{ projectId: projectID },
);
}, },
}); });
@ -346,21 +335,19 @@ const Project = () => {
const [createTask] = useCreateTaskMutation({ const [createTask] = useCreateTaskMutation({
onCompleted: newTaskData => {}, onCompleted: newTaskData => {},
update: (client, newTaskData) => { update: (client, newTaskData) => {
const cacheData = getCacheData(client, projectID); updateApolloCache<FindProjectQuery>(
const newTaskGroups = produce(cacheData.findProject.taskGroups, draftState => { client,
const targetIndex = draftState.findIndex( FindProjectDocument,
(taskGroup: any) => taskGroup.id === newTaskData.data.createTask.taskGroup.id, cache =>
); produce(cache, draftCache => {
draftState[targetIndex] = { const { taskGroups } = cache.findProject;
...draftState[targetIndex], const idx = taskGroups.findIndex(taskGroup => taskGroup.id === newTaskData.data.createTask.taskGroup.id);
tasks: [...draftState[targetIndex].tasks, { ...newTaskData.data.createTask }], if (idx !== -1) {
}; draftCache.findProject.taskGroups[idx].tasks.push({ ...newTaskData.data.createTask });
}); }
const newData = { }),
...cacheData.findProject, { projectId: projectID },
taskGroups: newTaskGroups, );
};
writeCacheData(client, projectID, cacheData, newData);
}, },
}); });
@ -444,12 +431,20 @@ const Project = () => {
const onListDrop = (droppedColumn: TaskGroup) => { const onListDrop = (droppedColumn: TaskGroup) => {
console.log(`list drop ${droppedColumn.id}`); console.log(`list drop ${droppedColumn.id}`);
const cacheData = getCacheData(client, projectID); updateApolloCache<FindProjectQuery>(
const newData = produce(cacheData, (draftState: any) => { client,
const taskGroupIdx = cacheData.findProject.taskGroups.findIndex((t: any) => t.id === droppedColumn.id); FindProjectDocument,
cacheData.findProject.taskGroups[taskGroupIdx].position = droppedColumn.position; cache =>
}); produce(cache, draftCache => {
writeCacheData(client, projectID, cacheData, newData); const taskGroupIdx = cache.findProject.taskGroups.findIndex(t => t.id === droppedColumn.id);
if (taskGroupIdx !== -1) {
draftCache.findProject.taskGroups[taskGroupIdx].position = droppedColumn.position;
}
}),
{
projectId: projectID,
},
);
updateTaskGroupLocation({ updateTaskGroupLocation({
variables: { taskGroupID: droppedColumn.id, position: droppedColumn.position }, variables: { taskGroupID: droppedColumn.id, position: droppedColumn.position },
optimisticResponse: { optimisticResponse: {
@ -481,12 +476,15 @@ const Project = () => {
const [updateProjectName] = useUpdateProjectNameMutation({ const [updateProjectName] = useUpdateProjectNameMutation({
update: (client, newName) => { update: (client, newName) => {
const cacheData = getCacheData(client, projectID); updateApolloCache<FindProjectQuery>(
const newData = { client,
...cacheData.findProject, FindProjectDocument,
name: newName.data.updateProjectName.name, cache =>
}; produce(cache, draftCache => {
writeCacheData(client, projectID, cacheData, newData); draftCache.findProject.name = newName.data.updateProjectName.name;
}),
{ projectId: projectID },
);
}, },
}); });
@ -739,17 +737,18 @@ const Project = () => {
deleteTask({ deleteTask({
variables: { taskID: cardId }, variables: { taskID: cardId },
update: () => { update: () => {
const cacheData = getCacheData(client, projectID); updateApolloCache<FindProjectQuery>(
const newData = { client,
...cacheData.findProject, FindProjectDocument,
taskGroups: cacheData.findProject.taskGroups.map((taskGroup: any) => { cache =>
return { produce(cache, draftCache => {
...taskGroup, draftCache.findProject.taskGroups = cache.findProject.taskGroups.map(taskGroup => ({
tasks: taskGroup.tasks.filter((t: any) => t.id !== cardId), ...taskGroup,
}; tasks: taskGroup.tasks.filter(t => t.id !== cardId),
}), }));
}; }),
writeCacheData(client, projectID, cacheData, newData); { projectId: projectID },
);
}, },
}) })
} }

View File

@ -6,6 +6,7 @@ import {
useGetProjectsQuery, useGetProjectsQuery,
useCreateProjectMutation, useCreateProjectMutation,
GetProjectsDocument, GetProjectsDocument,
GetProjectsQuery,
} from 'shared/generated/graphql'; } from 'shared/generated/graphql';
import ProjectGridItem, { AddProjectItem } from 'shared/components/ProjectGridItem'; import ProjectGridItem, { AddProjectItem } from 'shared/components/ProjectGridItem';
@ -17,6 +18,8 @@ import Button from 'shared/components/Button';
import { usePopup, Popup } from 'shared/components/PopupMenu'; import { usePopup, Popup } from 'shared/components/PopupMenu';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import Input from 'shared/components/Input'; import Input from 'shared/components/Input';
import updateApolloCache from 'shared/utils/cache';
import produce from 'immer';
const CreateTeamButton = styled(Button)` const CreateTeamButton = styled(Button)`
width: 100%; width: 100%;
@ -205,22 +208,11 @@ const Projects = () => {
}, []); }, []);
const [createProject] = useCreateProjectMutation({ const [createProject] = useCreateProjectMutation({
update: (client, newProject) => { update: (client, newProject) => {
const cacheData: any = client.readQuery({ updateApolloCache<GetProjectsQuery>(client, GetProjectsDocument, cache =>
query: GetProjectsDocument, produce(cache, draftCache => {
}); draftCache.projects.push({ ...newProject.data.createProject });
}),
console.log(cacheData); );
console.log(newProject);
const newData = {
...cacheData,
projects: [...cacheData.projects, { ...newProject.data.createProject }],
};
console.log(newData);
client.writeQuery({
query: GetProjectsDocument,
data: newData,
});
}, },
}); });
@ -228,17 +220,11 @@ const Projects = () => {
const { userID, setUserID } = useContext(UserIDContext); const { userID, setUserID } = useContext(UserIDContext);
const [createTeam] = useCreateTeamMutation({ const [createTeam] = useCreateTeamMutation({
update: (client, createData) => { update: (client, createData) => {
const cacheData: any = client.readQuery({ updateApolloCache<GetProjectsQuery>(client, GetProjectsDocument, cache =>
query: GetProjectsDocument, produce(cache, draftCache => {
}); draftCache.teams.push({ ...createData.data.createTeam });
const newData = { }),
...cacheData, );
teams: [...cacheData.teams, { ...createData.data.createTeam }],
};
client.writeQuery({
query: GetProjectsDocument,
data: newData,
});
}, },
}); });
if (loading) { if (loading) {

View File

@ -2,7 +2,13 @@ import React, { useState, useContext, useEffect } from 'react';
import styled from 'styled-components/macro'; import styled from 'styled-components/macro';
import { MENU_TYPES } from 'shared/components/TopNavbar'; import { MENU_TYPES } from 'shared/components/TopNavbar';
import GlobalTopNavbar from 'App/TopNavbar'; import GlobalTopNavbar from 'App/TopNavbar';
import { useGetTeamQuery, useDeleteTeamMutation, GetProjectsDocument } from 'shared/generated/graphql'; import updateApolloCache from 'shared/utils/cache';
import {
useGetTeamQuery,
useDeleteTeamMutation,
GetProjectsDocument,
GetProjectsQuery,
} from 'shared/generated/graphql';
import { useParams, useHistory } from 'react-router'; import { useParams, useHistory } from 'react-router';
import { usePopup, Popup } from 'shared/components/PopupMenu'; import { usePopup, Popup } from 'shared/components/PopupMenu';
import { History } from 'history'; import { History } from 'history';
@ -116,26 +122,14 @@ export const TeamPopup: React.FC<TeamPopupProps> = ({ history, name, teamID }) =
const { hidePopup, setTab } = usePopup(); const { hidePopup, setTab } = usePopup();
const [deleteTeam] = useDeleteTeamMutation({ const [deleteTeam] = useDeleteTeamMutation({
update: (client, deleteData) => { update: (client, deleteData) => {
const cacheData: any = client.readQuery({ updateApolloCache<GetProjectsQuery>(client, GetProjectsDocument, cache =>
query: GetProjectsDocument, produce(cache, draftCache => {
}); draftCache.teams = cache.teams.filter((team: any) => team.id !== deleteData.data.deleteTeam.team.id);
draftCache.projects = cache.projects.filter(
console.log(cacheData); (project: any) => project.team.id !== deleteData.data.deleteTeam.team.id,
console.log(deleteData); );
}),
const newData = produce(cacheData, (draftState: any) => { );
draftState.teams = draftState.teams.filter((team: any) => team.id !== deleteData.data.deleteTeam.team.id);
draftState.projects = draftState.projects.filter(
(project: any) => project.team.id !== deleteData.data.deleteTeam.team.id,
);
});
client.writeQuery({
query: GetProjectsDocument,
data: {
...newData,
},
});
}, },
}); });
return ( return (

View File

@ -198,7 +198,11 @@ const NavBar: React.FC<NavBarProps> = ({
{menuType && {menuType &&
menuType.map((name, idx) => { menuType.map((name, idx) => {
console.log(`${name} : ${idx} === ${currentTab}`); console.log(`${name} : ${idx} === ${currentTab}`);
return <ProjectTab active={currentTab === idx}>{name}</ProjectTab>; return (
<ProjectTab key={idx} active={currentTab === idx}>
{name}
</ProjectTab>
);
})} })}
</ProjectTabs> </ProjectTabs>
)} )}

View File

@ -0,0 +1,33 @@
import { DataProxy } from '@apollo/client';
import { DocumentNode } from 'graphql';
type UpdateCacheFn<T> = (cache: T) => T;
export function updateApolloCache<T>(
client: DataProxy,
document: DocumentNode,
update: UpdateCacheFn<T>,
variables?: object,
) {
let queryArgs: DataProxy.Query<any>;
if (variables) {
queryArgs = {
query: document,
variables,
};
} else {
queryArgs = {
query: document,
};
}
const cache: T | null = client.readQuery(queryArgs);
if (cache) {
const newCache = update(cache);
client.writeQuery({
...queryArgs,
data: newCache,
});
}
}
export default updateApolloCache;