The 'doRequest' property is not found on the type 'any[]'

Attempting to develop a custom hook in TypeScript for managing errors & API requests, but encountering a type error where a property does not exist on type 'any[]'

Here is the code for the hook:

import axios from 'axios';
import { useState } from 'react';

interface params {
    method: string;
    body: object;
    url: string;
}

interface reqParam {
    message: string;
    errors: string[];
}

const useRequest = ({url, method, body}: params) => {
    const [errors, setErrors] = useState(null);

    const doRequest: () => Promise<{} | null> = async () => {
        try {
            const response = await axios[method](url, body);
            return response.data;
        } catch (err) {
            setErrors(
                <div className="alert alert-danger">
                <h4>Oooops.....</h4>
                <ul className="mu-0">
                {err.response.data.errors.map((e: reqParam) => <li key={e.message}>{e.message}</li>)}
                </ul>
            </div>
            )
        }
    };

    return [doRequest, errors];
};

export default useRequest;

If a demonstration of the expected response output is necessary, please let me know and I can provide an example.

The sign up file includes the following code:

import { useState } from "react";
import useRequest from "../../hooks/use-request";

const signUp = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const {doRequest, errors} = useRequest({
        url: '/api/users/signup',
        method: 'post',
        body: {
            email, password
        }
    });

    const onSubmit = async (e: { preventDefault: () => void; }) => {
        e.preventDefault();
        doRequest();
    };
    return (
        <form onSubmit={onSubmit} className="container">
            <h1>signup</h1>
            <div className="form-group">
                <label>email</label>
                <input 
                    value={email} 
                    onChange={e => setEmail(e.target.value)} 
                    className="form-control" 
                />
            </div>
            <div className="form-group">
                <label>password</label>
                <input 
                    value={password} 
                    onChange={e => setPassword(e.target.value)} 
                    type="password" 
                    className="form-control" 
                />
            </div>
        {errors}
            
            <button className="btn btn-primary">Sign Up</button>
        </form>
    )
}

export default signUp;

Any assistance in identifying the issue would be greatly appreciated. The information provided should be sufficient, but if more details are needed, please don't hesitate to reach out. Thank you

Answer №1

The main issue at hand is the way you are handling the return value in your hook:

return [doRequest, errors];

However, you are mistakenly attempting to destructure it as if it were a standard object:

const {doRequest, errors} = useRequest(...)

What you actually should be doing is:

const [doRequest, errors] = useRequest(...)

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

Implement type declarations for a React JS form validation schema

I encountered the following scenario: interface FORM<P> { onSubmit: (d: P) => void; schema?: yup.SchemaOf<P>; } This is an example of my onSubmit function: const onSubmit = (d: { firstName: string; lastName: string }) => { conso ...

React type-script does not trigger the onClick event for CheckBox

I have created a custom component called MyCheckBox (which I am using as a helper component). I imported this component into another one, but for some reason, the event is not being triggered when I try to click on it. Here is the code for reference: MyC ...

Select a random index and modify it until all unique options have been exhausted, then restart the process

My image gallery has 6 slots for images, and I have an array with a certain number of image objects: "src" : { "1x" : "/clients/Logo-1.png", "2x" : "/clients/<a href="/cdn-cg ...

Using TypeScript and NestJs: Spread types can only be generated from object types

I'm encountering an issue while trying to pass two parameters using the spread operator from the book.controller to the book.service.ts service. The error message I'm receiving is: Spread types may only be created from object types It's w ...

On production, Heroku fails to load JavaScript files, only allowing CSS files to be loaded. However, the files load successfully when

I've been struggling to find a solution to my problem, so I'm reaching out for some help. I am in the process of deploying my node (express) app to Heroku, but I've encountered an issue where only CSS files from my public folder are being t ...

The next-redux-wrapper package experiences a quirk where useSelector returns an initial value of null after hydration, but getServerSideProps successfully passes the correct value to the

Currently, I am using getServerSideProps to fetch user data with an RTKQ endpoint by obtaining a token from a cookie and then dispatching the data to authSlice. Everything seems to be working well so far. const getServerSideProps = wrapper.getServerSidePr ...

What is causing ESLint to point out the issue with the @inheritdoc tag?

My code in ESLint is throwing an error about a missing JSDoc return declaration, even though I have included an @inheritdoc tag there: https://i.sstatic.net/QGxQh.png Here is the section from the interface I am inheriting from: export interface L2BlockSo ...

Changes in tabs are discarded when switching between them within Material UI Tabs

I have been experiencing an issue with the Material UI tab component where changes made in tabs are discarded when switching between them. It seems that after switching, the tabs are rendered again from scratch. For example, let's say I have a textFie ...

Using TypeScript to define values with the placeholder "%s" while inputting an object as a parameter

One common way to decorate strings is by using placeholders: let name = "Bob"; console.log("Hello, %s.", name) // => Outputs: "Hello, Bob." I'm curious if there's a way to access specific values within an object being passed in without specif ...

Ensuring external library object properties are limited in Typescript

Trying to utilize the notify function from an external library has been a bit challenging. The declaration in the library is as follows: // library.js export declare const notify: { (args: NotificationsOptions | string): void; close(id: unknown): ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

Explaining the structure of a nested object within a TypeScript declaration file

As I work on my project, I encounter the challenge of importing an object created by a dynamic function. The dynamic nature of the keys on this object poses a problem for the IDE, as it cannot determine what keys are present based on the provided config. T ...

What is the method for acquiring a dynamic segment in the router of a Next.js 13 application?

Currently in my project, I am using the new App Router in Next.js 13 and MongoDB as the DBMS to fetch data via API. When trying to retrieve all data from a collection, it is successful. However, fetching only one data results in failure. The error message ...

Using parameters and data type in Typescript

When I remove <IFirst extends {}, ISecond extends {}> from the declaration of this function, the compiler generates an error. Isn't the return value supposed to be the type after the double dot? What does <IFirst extends {}, ISecond extends { ...

Nuxt encountered an issue with Vue hydration: "Tried to hydrate existing markup, but the container is empty. Resorting to full mount instead."

I'm facing an issue while trying to integrate SSR into my project. I keep encountering this error/warning. How can I pinpoint the problem in my code? There are numerous components in my project, so I'm unsure if I should share all of my code, b ...

Implementing server-side middleware for individual routes in Next.js

I am currently exploring options for executing code upon the initial page load of each request. My goal is to determine the domain of the request and redirect to a specific section of the website based on this information. One possibility I have considere ...

Tips for defining a function across a Angular project

I have the following configuration set up in an Angular5 project using Angular-cli 1.5 within typings.d.ts declare interface String { toSentenceCase(): string; } declare function _debug(o, message?, type?): void; inside app/core/common.ts String.pro ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...