Skip to content

Commit

Permalink
perf: 불필요한 user api 요청 제거
Browse files Browse the repository at this point in the history
  • Loading branch information
wildcatco committed Aug 23, 2023
1 parent ced072c commit 75d6e21
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 12 deletions.
11 changes: 8 additions & 3 deletions src/features/posts/queries/useAddPost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@ export function useAddPost() {
return useMutation({
mutationFn: addPost,
onSuccess: () => {
queryClient.refetchQueries({
queryKey: ['posts'],
});
Promise.all([
queryClient.invalidateQueries({
queryKey: ['posts'],
}),
queryClient.invalidateQueries({
queryKey: ['user'],
}),
]);
},
});
}
12 changes: 6 additions & 6 deletions src/features/user/queries/useUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ export function useUser() {
queryKey: ['user'],
queryFn: getUser,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
initialData: userLocalStorage.getUser(),
retry: false,
initialData: userLocalStorage.getUser() || undefined,
initialDataUpdatedAt: userLocalStorage.getUserUpdatedAt(),
staleTime: 1000 * 60 * 5, // 5분
});

const user: User | null = useMemo(
Expand Down Expand Up @@ -53,12 +53,12 @@ export function useUser() {
);

useEffect(() => {
if (!user) {
if (!data) {
userLocalStorage.removeUser();
} else {
userLocalStorage.saveUser(user);
userLocalStorage.saveUser(data);
}
}, [user]);
}, [data]);

useEffect(() => {
if (isError) {
Expand Down
17 changes: 14 additions & 3 deletions src/features/user/utils/user-local-storage.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
import { User } from '../types';
import { GetUserResponse } from '@/features/user/queries/dto/get-user';

const USER_LOCAL_STORAGE_KEY = 'GOCHAM-USER';
const USER_UPDATED_AT_STORAGE_KEY = 'GOCHAM-USER-UPDATED-AT';

export const userLocalStorage = {
saveUser: (user: User) => {
saveUser: (user: GetUserResponse) => {
localStorage.setItem(USER_LOCAL_STORAGE_KEY, JSON.stringify(user));
localStorage.setItem(
USER_UPDATED_AT_STORAGE_KEY,
String(new Date().getTime()),
);
},
getUser: (): User | null => {
getUser: (): GetUserResponse | null => {
const user = localStorage.getItem(USER_LOCAL_STORAGE_KEY);
return user ? JSON.parse(user) : null;
},

getUserUpdatedAt: () => {
const updatedAt = localStorage.getItem(USER_UPDATED_AT_STORAGE_KEY);
return updatedAt ? Number(updatedAt) : null;
},

removeUser: () => {
localStorage.removeItem(USER_LOCAL_STORAGE_KEY);
},
Expand Down

0 comments on commit 75d6e21

Please sign in to comment.