Skip to content

[UNI-140] feat : 제보 Form API 연결 #65

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

Merged
merged 4 commits into from
Feb 6, 2025
Merged

[UNI-140] feat : 제보 Form API 연결 #65

merged 4 commits into from
Feb 6, 2025

Conversation

jpark0506
Copy link
Contributor

@jpark0506 jpark0506 commented Feb 6, 2025

#️⃣ 작업 내용

  1. 제보 Form API를 연결했습니다
  2. fallback의 console.log을 삭제했습니다.

핵심 기능

Form State를 Enum Key Type으로 변경했습니다.

백엔드 요청이 전부 Key값으로 요청이 전달되어, Key값으로 State가 저장되도록 변경했습니다.

export const SecondaryFormButton = ({
	onClick,
	formPassableStatus,
	isSelected,
	contentKey,
}: {
	onClick: (answer: IssueTypeKey) => void;
	formPassableStatus: PassableStatus;
	isSelected: boolean;
	contentKey: IssueTypeKey;
}) => {
	return (
		<button
			onClick={() => onClick(contentKey)}
			className={`mb-3 mr-3 py-[18px] px-[22px] border-[1px] rounded-[20px] w-fit text-kor-body2 border-gray-400 ${isSelected && getThemeByPassableStatus(formPassableStatus)}`}
		>
			{formPassableStatus === PassableStatus.CAUTION
				? CautionIssue[contentKey as CautionIssueType]
				: DangerIssue[contentKey as DangerIssueType]}
		</button>
	);
};

Form 로직 이슈 해결

  • 수정 상태에서 danger, caution state들이 서로 왔다갔다 할 때, 값이 보존되는 버그가 있어 해결했습니다
const handlePrimarySelect = (status: PassableStatus) => {
		setFormData((prev) => ({
			passableStatus: status === prev.passableStatus ? PassableStatus.INITIAL : status,
			dangerIssues: status === prev.passableStatus ? prev.dangerIssues : [],
			cautionIssues: status === prev.passableStatus ? prev.cautionIssues : [],
		}));
	};

useSuspenseQuery를 사용해 Form 데이터 Initialize

	const { data } = useSuspenseQuery({
		queryKey: ["user", university?.id ?? 1001, routeId],
		queryFn: async () => {
			try {
				const data = await getSingleRouteRisk(university?.id ?? 1001, routeId);
				return data;
			} catch (e) {
				return {
					routeId: -1,
					dangerTypes: [],
					cautionTypes: [],
				};
			}
		},
		retry: 1,
	});

	// 임시 Error 처리
	useEffect(() => {
		if (data.routeId === -1) {
			queryClient.invalidateQueries({ queryKey: ["report", university?.id ?? 1001, routeId] });
			setErrorTitle("존재하지 않은 경로예요");
			openFail();
		}
	}, [data]);

우선 길이 존재하지 않을 경우 케이스는 data.routeId를 -1 처리해 존재하지 않는 경로라고 처리했습니다.

post fetch 배열에 맞게 변경 및 response를 boolean으로 통일

const post = async <T, K>(url: string, body?: Record<string, K | K[]>): Promise<boolean> => {
		const response = await fetch(`${baseURL}${url}`, {
			method: "POST",
			body: JSON.stringify(body),
			headers: {
				"Content-Type": "application/json",
			},
		});

		if (!response.ok) {
			throw new Error(`${response.status}-${response.statusText}`);
		}

		return response.ok;
	};

제보 등록시 Mutation

	const { mutate } = useMutation({
		mutationFn: () =>
			postReport(university?.id ?? 1001, routeId, {
				dangerTypes: formData.dangerIssues,
				cautionTypes: formData.cautionIssues,
			}),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["report", university?.id ?? 1001, routeId] });
			openSuccess();
		},
		onError: () => {
			setErrorTitle("제보에 실패하였습니다");
			openFail();
		},
	});

동작 화면

데이터가 존재하고, 수정해야할 때

2025-02-06.17.54.17.mov

존재하지 않은 경로일 때

2025-02-06.17.54.50.mov

Copy link

coderabbitai bot commented Feb 6, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@dgfh0450 dgfh0450 left a comment

Choose a reason for hiding this comment

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

LGTM! 고생하셨습니다~

transform 패턴 아이디어는 매우 좋은 것 같습니다!

Comment on lines +30 to +36
dangerTypes: IssueTypeKey[];
cautionTypes: IssueTypeKey[];
}> => {
return getFetch<{
routeId: NodeId;
dangerTypes: IssueTypeKey[];
cautionTypes: IssueTypeKey[];
Copy link
Contributor

Choose a reason for hiding this comment

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

각 dangerTypes와 cautionTypes는 enum.d.ts의 DangerIssueType[] 으로 반영하면 더 엄격한 타입이 될 것 같습니다~

Comment on lines +24 to +26
headers: {
"Content-Type": "application/json",
},
Copy link
Contributor

Choose a reason for hiding this comment

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

제가 놓친 부분 수정 감사합니다~

@dgfh0450 dgfh0450 merged commit 1118bb9 into fe Feb 6, 2025
1 check passed
@jpark0506 jpark0506 self-assigned this Feb 6, 2025
@jpark0506 jpark0506 added 🚀 feat 기능 개발 🧇 fe 프론트엔드 task labels Feb 6, 2025
@jpark0506 jpark0506 deleted the feat/UNI-140 branch February 7, 2025 10:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🧇 fe 프론트엔드 task 🚀 feat 기능 개발
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants