reactjstypescriptvite

how to fix this typescript error: Type 'string' is not assignable to type 'RequestCredentials | undefined'


I'm a beginner learning React with typescript in a Vite environment. I have a register function that will send a fetch request to the server to register a user, I noticed the cookies sent back to the server are not recorded in the network tab(chrome dev tools) I figured out that I misspelled the credentials to credential. when I fixed it now it worked perfectly fine. Everything is good and the app is running even tho there is a typescript error,

how to fix this problem error in the option parameter?: fetch(....ulr, option);`?

Argument of type '{ method: string; headers: { "Content-Type": string; }; body: string; credentials: string; }' is not assignable to parameter of type 'RequestInit'.
  Types of property 'credentials' are incompatible.
    Type 'string' is not assignable to type 'RequestCredentials | undefined'.

here is my code:

import { RegisterProps } from "../pages/Register";

export const register = async (formData: RegisterProps) => {
  const API_URI = import.meta.env.VITE_BASE_URL;
  //specify the options
  const option = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(formData),
    credentials: "include",
  };
  //fetch request
  const response = await fetch(`${API_URI}/apiv1/auth/register`, option);
  //data response form the server
  const data = await response.json();
  if (!response.ok) {
    throw new Error(data.message);
  }
};

Solution

  • You can add : RequestInit after const option, like this:

    const option: RequestInit = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({}),
      credentials: 'include',
    };