inflearn logo
강의

講義

知識共有

Next + React Query で SNS サービスを作成する

クライアントコンポーネントでServer Actionsを使う

타입스크립트 질문

1125

dongwook98

投稿した質問数 19

0

useFormState initialState부분 타입스크립트 에러 질문입니다.

message에 string이 와야한다고 에러가 뜨는데 이거를 string | null로 해주는 방법을 잘 모르겠습니다!

const initialState: {
  message: string | null;
} = {
  message: null,
};

export default function SignupModal() {
  const [state, formAction] = useFormState(onSubmit, initialState);
  const { pending } = useFormStatus();

일단 이런식으로 빼서 에러 없애긴하였는데 인라인으로는 못하나요?

react next.js react-query next-auth msw

回答 3

2

gga01075

저 강사님분처럼 해봤는데도 에러가 뜨네용...

signupModal.tsx

import onSubmit from "../_lib/signup";

  const [state, formAction] = useFormState<{ message: string | null }>(onSubmit, { message: null });

signup.ts 파일

"use server";

import {redirect} from "next/navigation";

export default async (prevState: any, formData: FormData) => {
  if (!formData.get('id') || !(formData.get('id') as string)?.trim()) {
    return { message: 'no_id' };
  }
  if (!formData.get('name') || !(formData.get('name') as string)?.trim()) {
    return { message: 'no_name' };
  }
  if (!formData.get('password') || !(formData.get('password') as string)?.trim()) {
    return { message: 'no_password' };
  }
  if (!formData.get('image')) {
    return { message: 'no_image' };
  }
  let shouldRedirect = false;
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/users`, {
      method: 'post',
      body: formData,
      credentials: 'include',
    })
    console.log(response.status);
    if (response.status === 403) {
      return { message: 'user_exists' };
    }
    console.log(await response.json())
    shouldRedirect = true;
    await signIn("credentials", {
      username: formData.get('id'),
      password: formData.get('password'),
      redirect: false,
    })
  } catch (err) {
    console.error(err);
    return;
  }

  if (shouldRedirect) {
    redirect('/home'); // try/catch문 안에서 X
  }
}

이렇게 했는데 useFormState의 onSubmit부분에서 밑의 코드처럼 에러가 발생하네요ㅠㅠㅠㅠ

Argument of type '(prevState: any, formData: FormData) => Promise<{ message: string; } | undefined>' is not assignable to parameter of type '(state: { message: string | null; }) => { message: string | null; } | Promise<{ message: string | null; }>'.
  Target signature provides too few arguments. Expected 2 or more, but got 1.

0

zerocho

이 부분 뒷 강의(조금 많이 뒤)에서 해결하니까 무시하셔도 됩니다. signup.ts return 부분에 { message: null } 넣으면 됩니다.

0

zerocho

https://github.com/ZeroCho/next-app-router-z/blob/master/ch4/src/app/(beforeLogin)/_lib/signup.ts

 

0

sponjjanc1914

위에 사진에 보면 initialState: { message: string; } | undefined 로 되어있는데요
initialState: {message: string | null } | undefined
하시면 되지 않을까요?
그나저나 굳이 인라인 타입으로 할 이유가 있을까요?

0

dongwook98

저건 제가 해본거라 궁금해서 물어본거에요

0

sponjjanc1914

아하 그렇군여 이렇게 작성하면 되지않을까 싶습니다!

1. useFormState<{message: string | null}>
2. type FormState = { message: string | null }
   useFormState<FormState>(onSubmit, {message: null});

 

캡처링부분 질문있습니다.

0

74

2

깃에 소스코드를 찾을 수 없습니다.

0

113

2

useInfiniteQuery promise와 react use 사용시 페이지 무한 로딩

0

98

1

import 파일 경로를 찾지 못 해서 에러가 발생합니다.

0

109

2

css 라이브러리 추천 부탁드립니다

0

140

2

팔로우 추천 목록이 빈 배열로 들어옵니다.

0

130

1

게시물 업로드 시 userId가 undefined로 들어가는 오류

0

119

1

useSuspenseQuery 사용 시 SSR 401 이슈 관련

0

172

1

리액트 쿼리 useinfinitequery 무한스크롤 구현 시 페이지가 이동할 경우 데이터가 보존되게 할 수 있나요??

0

184

3

폴링이 필요없는 이유

0

93

2

next Request Memoization과 react cache

0

108

2

seo 최적화 기준은 데이터 fetching인가요 아님 데이터 렌더링인가요?

0

84

2

next.js 서버fetch 에러 fallback ui 구현 방법

0

173

2

프레임워크 여론 파악법

0

125

2

필터옵션이 많은 페이지에서 서버 fetch를 하는게 맞는걸까요??

0

103

2

서버 fetch suspense 로 감싸고 새로고침 시 잠시 빈 화면이 노출된 후 fallback ui가 노출됩니다.

0

102

2

template.tsx 내 서버fetch 응답값과 클라이언트 컴포넌트 상태값 싱크가 맞지 않는 이슈

0

66

2

Auth.js 사용 시 authorize 함수가 호출되지 않습니다

0

132

2

next.js 에서 로그인에 관하여

0

138

1

Next의 route handler에 대한 질문이 있습니다.

0

101

2

게시판 리스트 만들때 use client를 어디서부터 집어넣어야할지 모르겠습니다

0

98

2

프라이빗 폴더를 해야 하는 이유가 모호한 것 같아요.

0

85

2

vanilla-extract 못찾는 문제

0

230

2

fetch 캐싱과 revalidate 관련

0

84

2