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

feature(web): survey데이터 호출 #5

Open
wants to merge 1 commit into
base: style/admin
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
9 changes: 9 additions & 0 deletions apps/survey-web/src/app/app.css.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { style } from '@vanilla-extract/css';

export const container = style({
margin: 'auto',
maxWidth: '90vw',
width: '640px',
marginTop: '12px',
marginBottom: '12px',
});
17 changes: 5 additions & 12 deletions apps/survey-web/src/app/app.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,22 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { SharedUi } from '@ssoon-servey/shared-ui';
import { Route, Routes, Link } from 'react-router-dom';
import { container } from './app.css';
import SurveyPage from './survey/page';

export function App() {
return (
<div>
<SharedUi />
<div className={container}>
<Routes>
<Route
path="/"
element={
<div>
This is the generated root route.{' '}
<Link to="/page-2">Click here for page 2.</Link>
</div>
}
/>
<Route
path="/page-2"
element={
<div>
<Link to="/">Click here to go back to root page.</Link>
<Link to="/survey/1">Click here for page survey.</Link>
</div>
}
/>
<Route path="/survey/:id" element={<SurveyPage />} />
</Routes>
{/* END: routes */}
</div>
Expand Down
111 changes: 111 additions & 0 deletions apps/survey-web/src/app/survey/hooks/useSurvey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import {
SupabaseContextValue,
useSupabaseContext,
} from '@ssoon-servey/supabase';
import { useEffect, useState } from 'react';

type Options = {
id: number;
option_text: string;
item_id: number | null;
};

type SurveyItems = {
id: number;
options: Options[];
question_required: boolean;
question_title: string;
question_type: string;
section_id: number | null;
};

type SurveySections = {
id: number;
survey_title: string | null;
survey_id: number | null;
items: SurveyItems[];
isNext: boolean;
isPrevious: boolean;
};

type Survey = {
id: number;
title: string;
description?: string | null;

sections: SurveySections[];
};

type apiState<T> =
| {
data: null;
isLoading: false;
isError: true;
}
| {
data: null;
isLoading: true;
isError: false;
}
| {
data: T;
isLoading: false;
isError: false;
};

const getSurvey = async (supabase: SupabaseContextValue['supabase']) => {
const { data: surveys } = await supabase
.from('surveys')
.select('id,title,description');
if (!surveys) return null;

const _survey = surveys[0];

const { data: sections } = await supabase.from('survey_sections').select('*');
if (!sections) return null;

const { data: items } = await supabase.from('survey_items').select('*');
if (!items) return null;

const { data: options } = await supabase.from('question_options').select('*');
if (!options) return null;

const survey: Survey = {
..._survey,
sections: sections.map((section, i) => ({
...section,
isNext: i !== sections.length - 1,
isPrevious: i !== 0,
items: items
.filter((item) => item.section_id === section.id)
.map((items) => ({
...items,
options: options.filter((option) => option.item_id === items.id),
})),
})),
};
return survey;
};

const useGetSurvey = (): apiState<Survey> => {
const { supabase } = useSupabaseContext();
const [data, setData] = useState<Survey | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);

useEffect(() => {
getSurvey(supabase)
.then((data) => {
setData(data);
setIsLoading(false);
})
.catch(() => {
setIsError(true);
setIsLoading(false);
});
Comment on lines +97 to +105

Choose a reason for hiding this comment

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

p2: getSurvey는 async await을 사용하신반면, 여기는 Promise를 사용하셨는데요 통일하는게 좋지 않을까요?
그리고, useQuery에서 getSurvey를 불러오게도 사용하실 수 있을 것 같아요 react-query를 사용하시면 에러처리를 suspense로 할 수 있는등의 이점이 있습니다

}, [supabase]);

return { data, isLoading, isError } as apiState<Survey>;
};

export { useGetSurvey };
24 changes: 24 additions & 0 deletions apps/survey-web/src/app/survey/page.css.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { vars } from '@ssoon-servey/shared-ui';
import { style } from '@vanilla-extract/css';

export const cardContainer = style({
display: 'flex',
flexDirection: 'column',
gap: '10px',
});

export const borderTop = style({
backgroundColor: vars.color.primary500,
borderTopLeftRadius: '8px',
borderTopRightRadius: '8px',
height: '10px',
position: 'absolute',
top: 0,
left: 0,
right: 0,
});

export const cardWrapper = style({
padding: '24px',
paddingTop: '22px',
});
66 changes: 66 additions & 0 deletions apps/survey-web/src/app/survey/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { useGetSurvey } from './hooks/useSurvey';
import { Block, Card } from '@ssoon-servey/shared-ui';
import * as $ from './page.css';
import { useNavigate, useParams } from 'react-router-dom';
import { useEffect } from 'react';

const INITIAL_ID = 1;

const SurveyPage = () => {
const { data, isError, isLoading } = useGetSurvey();
const { id } = useParams();
const sectionId = Number(id);

const navigate = useNavigate();

useEffect(() => {
navigate(`/survey/${INITIAL_ID}`, { replace: true });
}, []);

if (isError) {
return <div>error</div>;
}

if (isLoading) {
return <div>loading...</div>;
}
Comment on lines +20 to +26

Choose a reason for hiding this comment

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

p2: https://tech.kakaopay.com/post/react-query-2/ 여기 부분들도 Suspense도입과 에러처리 같이 해주시고,
추가로 Sentry 도입도 같이되어서 에러추적할 수 있게 설계해보시면 좋을 것 같습니다


const goNextSection = () => {
navigate(`/survey/${sectionId + 1}`);
};

const goBackSection = () => {
navigate(-1);
};

const sections = data.sections[sectionId - 1];

return (
<div className={$.cardContainer}>
<Card>
<div className={$.borderTop} />
<div className={$.cardWrapper}>
<span>{data?.title}</span>
<div>* 표시는 필수 질문임</div>
</div>
</Card>
{sections.items.map((item) => (
<Card key={item.id}>
<div className={$.cardWrapper}>
<div>{item.question_title}</div>
{item.options.map((option) => (
<div key={option.id}>{option.option_text}</div>
))}
</div>
</Card>
))}

<div>
{sections.isPrevious && <button onClick={goBackSection}>이전</button>}
{sections.isNext && <button onClick={goNextSection}>다음</button>}
</div>
</div>
);
};

export default SurveyPage;
7 changes: 5 additions & 2 deletions apps/survey-web/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import { StrictMode } from 'react';
import * as ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';

import { SupabaseProvider } from '@ssoon-servey/supabase';
import App from './app/app';
import '@ssoon-servey/shared-ui/css';

const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<StrictMode>
<BrowserRouter>
<App />
<SupabaseProvider supabaseKey={import.meta.env.VITE_SUPABASE_KEY}>
<App />
</SupabaseProvider>
</BrowserRouter>
</StrictMode>
);
3 changes: 2 additions & 1 deletion apps/survey-web/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';

export default defineConfig({
root: __dirname,
Expand All @@ -17,7 +18,7 @@ export default defineConfig({
host: 'localhost',
},

plugins: [react(), nxViteTsPaths()],
plugins: [react(), nxViteTsPaths(), vanillaExtractPlugin()],

// Uncomment this if you are using workers.
// worker: {
Expand Down
6 changes: 0 additions & 6 deletions libs/supabase/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,23 +37,20 @@ export type Database = {
};
survey_items: {
Row: {
hasOption: boolean | null;
id: number;
question_required: boolean;
question_title: string;
question_type: string;
section_id: number | null;
};
Insert: {
hasOption?: boolean | null;
id?: never;
question_required: boolean;
question_title: string;
question_type: string;
section_id?: number | null;
};
Update: {
hasOption?: boolean | null;
id?: never;
question_required?: boolean;
question_title?: string;
Expand All @@ -73,19 +70,16 @@ export type Database = {
survey_sections: {
Row: {
id: number;
section_id: number | null;
survey_id: number | null;
survey_title: string | null;
};
Insert: {
id?: never;
section_id?: number | null;
survey_id?: number | null;
survey_title?: string | null;
};
Update: {
id?: never;
section_id?: number | null;
survey_id?: number | null;
survey_title?: string | null;
};
Expand Down