"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function:

export interface IData {
  editable: string[];
  favourited: string[];
}

const [data, setData] = useState<IData | undefined>(undefined)

useEffect(() => {
    if (status === "authenticated") {
      fetchUserDoc(session?.user?.uid, setData);
    }
  }, [status]);

The utility function retrieves a document from Firestore and passes the data to the setter. If the document does not exist, it creates the document and then calls itself to repeat the process.

export interface IFetchDocProps {
  uid: string;
  setData: Dispatch<SetStateAction<DocumentData>>;
}

export default async function fetchUserDoc({
  uid,
  setData,
}: IFetchDocProps) {
  const docRef = doc(db, "users", uid);
  const docSnap = await getDoc(docRef);

  if (docSnap.exists()) {
    let data = docSnap.data();
    setData(data);
  } else {
    await setDoc(doc(db, "users", uid), {
      editable: [],
      favourited: [],
    });
    fetchUserDoc(uid, setData);
  }
}

Upon calling fetchUserDoc(uid, setData), the error

Expected 1 arguments, but got 2.ts(2554)
is displayed.

Could you provide any guidance on this issue? It seems like there may be confusion related to the interfaces at play here.

Answer №1

It's fairly straightforward - your function requires a single object as an argument, so the correct way to call it would be:

retrieveUserData({id, updateData});

Answer №2

The fetchUserDoc function is defined with a single parameter:

{
  uid,
  setData,
}: IFetchDocProps

Although the IFetchDocProps interface has two fields, when you call the function you only need to pass one parameter:

fetchUserDoc(uid, setData);

uid -> Param1 setData -> Param2

To resolve this issue, you should create an object with both attributes and pass it as a single parameter:

// Example pseudocode
// Create an object with both fields
let param = new IFetchDocProps( uid, setData )
// Call the function with a single parameter
fetchUserDoc( param )

These are just pseudocodes for illustrative purposes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arrange the data in the table according to a predetermined default column

As a newcomer to ReactJS, I've implemented a table where you can sort the data by clicking on each column header. Here's a snippet of my code: import React, { useState, useEffect } from 'react' import { getUsers } from '../../servi ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

Explore various domains using the material-ui autocomplete feature

I'm currently working with material-ui and autoComplete in ReactJS to search within a single domain. How can I modify it to search across multiple domains? In addition, I would like to include the customerSurname field. Currently searching based on ...

Optimal method for personalizing MUI 5 Drawer while avoiding CSS conflicts

Currently, I am exploring how to personalize MUI 5 components by leveraging theming and props more and minimizing the use of CSS overrides (which can negate the benefits of MUI). To start off, I have created my own theme: export const theme = createTheme( ...

The MUI persistent drawer navigation bar becomes dysfunctional when accessing a specific route

Exploring the MUI library for the first time, I successfully created a navigation bar that functions properly for one route (Dashboard). However, when attempting to implement it on the candidate route, it collapses as shown in this Screengrab of collapsed ...

Is it possible to devise a universal click handler in TypeScript that will consistently execute after all other click handlers?

In my ReactJS based application written in TypeScript, we have implemented various click handlers. Different teams contribute to the application and can add their own handlers as well. The challenge we face is ensuring that a specific global click handler ...

What is the best approach for incorporating a customized set of valid keywords into a text input field in JHipster while maintaining a sophisticated design?

My code snippet is not displaying the input even though all the necessary elements are in place: home.component.ts <p class="lead">Input: </p> <div><jhi-calculator-input></jhi-calculator-input></div> calculator.compon ...

Tips for efficiently passing TypeScript constants to Vue templates without triggering excessive reactivity

I'm curious about the most efficient way to pass a constant value to a template. Currently, I am using the data property in Vue, but I believe that is better suited for state that changes over time as Vue adds event listeners to data properties. The c ...

What could be causing the conditional div to malfunction in Angular?

There are three conditional div elements on a page, each meant to be displayed based on specific conditions. <div *ngIf="isAvailable=='true'"> <form> <div class="form-group"> <label for ...

Setting the "status" of a queue: A step-by-step guide

I created a function to add a job to the queue with the following code: async addJob(someParameters: SomeParameters): Promise<void> { await this.saveToDb(someParameters); try { await this.jobQueue.add('job', ...

Error in Node: resolve-url-loader - CSS resolution error

Trying to set up a React project as the development server on my Surface has been causing issues, unlike when I run the same configuration on my PC. Despite trying to replicate the same conditions, the problem persists. The error message received is: ./s ...

What is the best way to implement Angular translation for multiple values in a typescript file, while also incorporating parameters?

this.snackBar.open( `Only files of size less than ${this.fileSizeAllowed}KB are allowed`, this.translate.instant('USER_REG.close'), { panelClass: 'errorSnackbar', ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

Console displaying API results but not appearing in browser window

class App extends Component { state = { data: '' } componentDidMount() { axios.get(`https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=wikipedia&utf8=&format=json`) .then(res => ...

Transferring a JSON file between components within Angular 6 utilizing a service

I have been facing an issue in passing the response obtained from http.get() in the displayresults component to the articleinfo component. Initially, I used queryParams for this purpose but realized that I need to pass more complex data from my JSON which ...

Angular Test Error: Refactoring requires a source file to be present

Trying to execute the command ng test, I encountered an error message. How can this issue be resolved? I am unsure of its meaning. ERROR in Must have a source file to refactor. To eliminate this warning, use "ng config -g cli.warnings.versionMismatc ...

What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used? enum FormType { ...

How long does it typically take to build a ReactJS application with a Gatsby theme?

I'm currently working on a ReactJS application using a gatsby-theme, but the build time is taking over 6 minutes. Is this typical for this type of application? If not, what can I do to improve and optimize the build time for my gatsby-theme project? ...

From jQuery to ReactJS: Migrating to a Modern

As I venture into converting existing jQuery code to React.js, I must admit that I am quite new to React and still in the learning phase. So please bear with me if my questions sound a bit silly. Here is the structure I am working with: <ul> &l ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...