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

🐛 fix: issue where adding a keyword doesn't display the list of random sentences #43

Merged
merged 1 commit into from
Apr 6, 2024
Merged
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
2 changes: 1 addition & 1 deletion src/features/syntax-analyzer/api/get-random-sentences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const getRandomSentences = async <
export const RANDOM_SENTENCE_BASE_KEY = ['random-sentences'] as const;

export const useRandomSentenceQuery = <T = RandomSentenceResponse, K = T>(
params: RandomSentenceParams,
params: RandomSentenceParams & { timeStamp: number },
options?: Partial<UseQueryOptions<T, AxiosError, K>>,
) => {
return useQuery({
Expand Down
37 changes: 24 additions & 13 deletions src/features/syntax-analyzer/hooks/use-random-sentence-form.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useState } from 'react';

import { useBoolean } from '@chakra-ui/react';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';

import { useLocalStorage } from '@/base';
import {
randomSentenceFormSchema,
REMAINING_COUNT_BASE_KEY,
Expand All @@ -19,30 +19,41 @@ export type RandomSentenceFormValues = {
* yup 스키마의 cast 기능을 이용해 기본값 설정
* @see https://github.com/orgs/react-hook-form/discussions/1936
* */
const defaultValues = randomSentenceFormSchema.cast({});
const { topics, sent_count } = defaultValues;
const defaultFormValues = randomSentenceFormSchema.cast({});
const { topics, sent_count } = defaultFormValues;
const defaultParams = { topics, sent_count, timeStamp: Date.now() };

export const useRandomSentenceForm = () => {
const [params, setParams] = useState({ topics, sent_count });
const [readyToFetch, setReadyToFetch] = useBoolean();

const [params, setParams] = useLocalStorage(
'random-sentence-params',
defaultParams, // 기본값을 넘겼어도 로컬 스토리지에 key 값이 있으면 해당 값 사용
);

const methods = useForm<RandomSentenceFormValues>({
defaultValues,
defaultValues: {
...defaultFormValues,
topics: params.topics, // 로컬 스토리지에 있는 값을 기본값으로 설정
sent_count: params.sent_count,
},
resolver: yupResolver(randomSentenceFormSchema),
reValidateMode: 'onSubmit',
});

// 쿼리가 비활성화 되자마자 캐시를 삭제하고 싶으면 gcTime 쿼리 옵션을 0으로 설정
// 캐시 데이터가 있다면 쿼리가 활성화 됐을 때(마운트 등) 캐시 데이터 사용(staleTime 초과됐다면 리패치)
const { data, isFetching, refetch } = useRandomSentenceQuery(params, {
enabled: false, // 생성 버튼을 클릭했을 때만 수동으로 데이터 조회하므로 false로 설정
staleTime: Infinity, // 데이터를 수동으로 조회하므로 자동 refetch 방지
const { data, isFetching } = useRandomSentenceQuery(params, {
enabled: readyToFetch,
gcTime: 0, // 비활성화된 쿼리의 캐시 데이터는 바로 삭제
staleTime: Infinity, // 일회성 데이터를 수동으로 조회하므로 자동 refetch 방지
meta: { invalidateQueries: REMAINING_COUNT_BASE_KEY },
});

const generateSentences = async () => {
if (!readyToFetch) setReadyToFetch.on(); // 쿼리 활성화

const { topics, sent_count } = methods.getValues();
setParams({ topics, sent_count });
await refetch();
// timeStamp 값이 바뀌면서 이전 쿼리키가 비활성화 되고 캐시 데이터에서 삭제됨 (gcTime 0이므로)
setParams({ topics, sent_count, timeStamp: Date.now() });
};

return { methods, data, isFetching, generateSentences };
Expand Down
Loading