• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

타입스크립트 질문

23.12.11 05:32 작성 23.12.11 05:33 수정 조회수 734

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();

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

답변 3

·

답변을 작성해보세요.

2

gga01075님의 프로필

gga01075

2023.12.19

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

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

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

0

대원님의 프로필

대원

2023.12.11

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

신동마님의 프로필

신동마

질문자

2023.12.11

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

대원님의 프로필

대원

2023.12.12

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

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