Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bingo) bingo 부분에 reactQuery 추가 #34

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@fontsource/roboto": "^5.0.8",
"@mui/icons-material": "^5.15.4",
"@mui/material": "^5.15.4",
"@tanstack/react-query": "^5.51.11",
"@types/react-router-dom": "^5.3.3",
"dayjs": "^1.11.11",
"prettier": "^3.3.0",
Expand Down
41 changes: 23 additions & 18 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,35 +11,40 @@ import Board from "./modules/Community/index.tsx";
import BoardView from "./modules/Community/BoardView.tsx";
import { Container, CssBaseline } from "@mui/material";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

function App() {
const defaultTheme = createTheme();

const queryClient = new QueryClient();

return (
<ThemeProvider theme={defaultTheme}>
<BrowserRouter>
<CssBaseline />
<Container className="App">
<Header />
<Routes>
<Route path="/" Component={Home} />
<Route path="/builder" element={<IntroduceBuilder />} />
<Route path="/runner" element={<Test />} />
<Route path="/community/*" element={<Board />} />
<Route path="/bingo" element={<Bingo />} />
<Route path="/signup" element={<SignUpForm />} />
{/* <Route path="/posts" component={Posts} />
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={defaultTheme}>
<BrowserRouter>
<CssBaseline />
<Container className="App">
<Header />
<Routes>
<Route path="/" Component={Home} />
<Route path="/builder" element={<IntroduceBuilder />} />
<Route path="/runner" element={<Test />} />
<Route path="/community/*" element={<Board />} />
<Route path="/bingo" element={<Bingo />} />
<Route path="/signup" element={<SignUpForm />} />
{/* <Route path="/posts" component={Posts} />
<Route path="/posts/:id" component={Post} />
<Route path="/posts/new" component={NewPost} />
<Route path="/posts/edit/:id" component={EditPost} />
<Route path="/posts/delete/:id" component={DeletePost} />
<Route path="/posts/search/:query" component={Search} />
<Route path="/posts/search/:query/:page" component={Search} /> */}
</Routes>
<Footer />
</Container>
</BrowserRouter>
</ThemeProvider>
</Routes>
<Footer />
</Container>
</BrowserRouter>
</ThemeProvider>
</QueryClientProvider>
);
}

Expand Down
33 changes: 25 additions & 8 deletions src/api/bingo_api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const API_URL: string = import.meta.env.VITE_API_URL;
// const API_URL: string = import.meta.env.VITE_API_URL;
const API_URL: string = 'http://localhost:8000';

export const singUpUser = async (username: string) => {
const response = await fetch(
Expand All @@ -25,12 +26,13 @@ export const getUser = async (username: string) => {
return data;
};

export const createBingoBoard = async (
export const createBingoBoard = async (args: {
userId: string,
boardData: {
[key: string]: { value: string; status: number; selected: number };
}
) => {
}) => {
const { userId, boardData } = args;
const response = await fetch(`${API_URL}/api/bingo/boards`, {
method: "POST",
headers: {
Expand All @@ -42,6 +44,10 @@ export const createBingoBoard = async (
};

export const getBingoBoard = async (userId: string) => {
if (!userId) {
return;
}

const response = await fetch(`${API_URL}/api/bingo/boards/${userId}`);
if (response.ok === false) {
return [];
Expand All @@ -52,6 +58,7 @@ export const getBingoBoard = async (userId: string) => {
...boardData[key],
id: key,
}));
console.log(items);
return items;
};

Expand Down Expand Up @@ -83,11 +90,12 @@ export const updateBingoBoard = async (
return response.ok;
};

export const createUserBingoInteraction = async (
word_id_list: string | null,
send_user_id: number,
receive_user_id: number
) => {
export const createUserBingoInteraction = async (args: {
word_id_list: string | null;
send_user_id: number;
receive_user_id: number;
}) => {
const { word_id_list, send_user_id, receive_user_id } = args;
const response = await fetch(`${API_URL}/api/bingo/interactions`, {
method: "POST",
headers: {
Expand All @@ -99,6 +107,11 @@ export const createUserBingoInteraction = async (
};

export const getUserLatestInteraction = async (userId: string) => {

if (!userId) {
return;
}

const response = await fetch(`${API_URL}/api/bingo/interactions/${userId}`);

if (response.ok === false) {
Expand All @@ -109,6 +122,10 @@ export const getUserLatestInteraction = async (userId: string) => {
};

export const getUserName = async (userId: string) => {
if (!userId) {
return;
}

const response = await fetch(`${API_URL}/api/auth/bingo/get-user/${userId}`);
if (response.ok === false) {
return [];
Expand Down
27 changes: 27 additions & 0 deletions src/hooks/bingo/mutations/useCreateBingoBoardMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createBingoBoard } from "../../../api/bingo_api";
import QueryKeyGenerator from "../../common/QueryKeyGenerator";

export const useCreateBingoBoardMutation = async (sendUserId: string) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (args: {
userId: string,
boardData: {
[key: string]: { value: string; status: number; selected: number };
},
}) => {
const { userId, boardData } = args;
return createBingoBoard(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓혹시 이부분 광수님 환경에서는 잘 호출되실까요? 동작 테스트 해보려고 하는데 수정된 부분이 호출되지 않는것 같아서요

temp_0722.mov

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 이 부분은 호출은 됐는데, 저 같은 경우는 CORS나 bingo backend api 부분에서 발생한 이슈 때문에 안되는 것 같더라구요! 저도 좀 더 살펴보고 말씀드릴게요!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아!? 호출이 되는걸 확인하셨군요! 저도 잘못 설정한게 없는지 한번 더 확인해보겠습니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네네! 감사합니당 저도 좀 더 봐볼게욥

{
userId,
boardData,
}
);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: QueryKeyGenerator.bingoBoard(sendUserId) });
queryClient.invalidateQueries({ queryKey: QueryKeyGenerator.userLatestInteraction(sendUserId) });
}
});
}
29 changes: 29 additions & 0 deletions src/hooks/bingo/mutations/useCreateUserBingoInteractionMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createUserBingoInteraction } from "../../../api/bingo_api";
import QueryKeyGenerator from "../../common/QueryKeyGenerator";

export const useCreateUserBingoInteractionMutation = async (sendUserId: string) => {
const queryClient = useQueryClient();
// 새로운 interaction을 생성하는 mutation입니다.
return useMutation({
mutationFn: (args: {
word_id_list: string | null,
send_user_id: number,
receive_user_id: number
}) => {
const { word_id_list, send_user_id, receive_user_id } = args;
return createUserBingoInteraction(
{
word_id_list,
send_user_id,
receive_user_id
}
);
},
onSuccess: () => {
// 새로운 interaction이 생성되면, 해당 유저의 bingo board와 latest interaction을 업데이트합니다.
queryClient.invalidateQueries({ queryKey: QueryKeyGenerator.bingoBoard(sendUserId) });
queryClient.invalidateQueries({ queryKey: QueryKeyGenerator.userLatestInteraction(sendUserId) });
}
});
};
16 changes: 16 additions & 0 deletions src/hooks/bingo/useBingoBoardByUserId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useQuery } from "@tanstack/react-query";
import QueryKeyGenerator from "../common/QueryKeyGenerator";
import { getBingoBoard } from "../../api/bingo_api";

export const useBingoBoardByUserId = (userId: string) => {
return useQuery({
queryKey: QueryKeyGenerator.bingoBoard(userId), // 쿼리 키를 통해서 쿼리들을 구분합니다. 나중에 쿼리키를 활용해서 해당 쿼리들을 reset 할 수 있습니다.
queryFn: () => { // 쿼리 함수
const data = getBingoBoard(userId)
if (!data) {
throw new Error("Bingo board not found");
}
return data;
}
});
}
16 changes: 16 additions & 0 deletions src/hooks/bingo/useUserLatestInteractionByUserId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useQuery } from "@tanstack/react-query";
import QueryKeyGenerator from "../common/QueryKeyGenerator";
import { getUserLatestInteraction } from "../../api/bingo_api";

export const useUserLatestInteractionByUserId = (userId: string) => {
return useQuery({
queryKey: QueryKeyGenerator.userLatestInteraction(userId),
queryFn: () => {
const data = getUserLatestInteraction(userId)
if (!data) {
throw new Error("User latest interaction not found");
}
return data;
}
});
}
5 changes: 5 additions & 0 deletions src/hooks/common/QueryKeyGenerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
user: (username: string) => ['user', username],
bingoBoard: (userId: string) => ['bingoBoard', userId],
userLatestInteraction: (userId: string) => ['userLatestInteraction', userId],
}
16 changes: 16 additions & 0 deletions src/hooks/user/useUserById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useQuery } from "@tanstack/react-query";

import { getUser as getUserByUsername } from "../../api/bingo_api";
import QueryKeyGenerator from "../common/QueryKeyGenerator";

export const useUserByUsername = (username: string) => {
return useQuery({
queryKey: QueryKeyGenerator.user(username), queryFn: () => {
const data = getUserByUsername(username)
Comment on lines +6 to +9
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

export const useUserByUsername = async (username: string) => {
    return useQuery({
        queryKey: QueryKeyGenerator.user(username), queryFn: () => {
            const data = await getUserByUsername(username)

와 같이 하면 정상적으로 데이터가 가져와집니다.

if (!data) {
throw new Error("User not found");
}
return data;
}
});
};
Loading