I seem to be missing something: Unhandled Rejection (TypeError): setToken function is not recognized

I am a beginner in React and TypeScript and I am facing an issue while trying to implement a basic functionality. Unfortunately, I keep encountering the error: Unhandled Rejection (TypeError): setToken is not a function. Can anyone provide me with some guidance?

App.tsx

import React from "react"
import './App.css';
import VacationManager from "./VacationManager";
import Login from './Login';

function App() {
    const [token, setToken] = React.useState<string | null>(null);

    if(!token) {
        return <Login setToken={setToken} />;
    }

    return <div className="App">
        <div className="Header"></div>
        <div className="App-Body">
            <VacationManager />
        </div>
    </div>;
}

export default App;

Login.tsx

import React from 'react';
import PropTypes from 'prop-types';
import './Login.css';

async function loginUser(credentials: { username:string | null, password:string | null }) {
   return (credentials.username === "test" && credentials.password === "test") ? "new_login_state" : null;
}

function Login(setToken: React.Dispatch<React.SetStateAction<string | null>>) {
    const [username, setUserName] = React.useState<string | null>(null);
    const [password, setPassword] = React.useState<string | null>(null);

    const handleSubmit = async (e: { preventDefault: () => void; }) => {
        e.preventDefault();
        const token = await loginUser({
            username,
            password
        });
        setToken(token);
    }

    return <div className="login-wrapper">
        <h1>Please Log In</h1>
        <form onSubmit={handleSubmit}>
            <label>
                <p>Username</p>
                <input type="text" onChange={e => setUserName(e.target.value)}/>
            </label>
            <label>
                <p>Password</p>
                <input type="password" onChange={e => setPassword(e.target.value)}/>
            </label>
            <div>
                <button type="submit">Submit</button>
            </div>
        </form>
    </div>;
}

Login.propTypes = {
    setToken: PropTypes.func.isRequired
}

export default Login;

Upon entering the username and password, I encounter the aforementioned error. My intention is to pass the setter to the Login component for updating the token status. This example serves as a simple starting point, yet I seem to be missing something in my implementation.

Answer №1

When working with the login component, make sure to use an object as the first parameter which includes properties such as setToken. Here's how you can modify it:

interface LoginProps {
  setToken: React.Dispatch<React.SetStateAction<string | null>>;
}

function Login({ setToken }: LoginProps) {
  ...
}

Answer №2

function UserLogin(updateToken: React.Dispatch<React.SetStateAction<string | null>>) 
{
  const [user, setUser] = React.useState<string | null>(null);
  const [pass, setPass] = React.useState<string | null>(null);
  const [authToken, setAuthToken] = useState('');

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

Anticipated the object to be a type of ScalarObservable, yet it turned out to be an

When working on my Angular project, I utilized Observables in a specific manner: getItem(id): Observable<Object> { return this.myApi.myMethod(...); // returns an Observable } Later, during unit testing, I successfully tested it like so: it(&apos ...

Encountering a sign-in issue with credentials in next-auth. The credential authorization process is resulting in a

I am currently facing an issue with deploying my Next.js project on Vercel. While the login functionality works perfectly in a development environment, I encounter difficulties when trying to sign in with credentials in Production, receiving a 401 error st ...

What are the various functions that an Alert button can serve in Ionic?

What are the potential choices for the role designation of a button within an Alert using the Ionic framework (v5)? The official documentation only lists cancel: https://ionicframework.com/docs/api/alert#buttons If desired, a button can have a role prop ...

Displaying dynamic key-value pairs in each row of an Angular mat-table

I need help displaying a key-value pair data in JSON format dynamically within a table using Angular mat-table. The keys will vary, so there is no set list of keys that will be included in the JSON. This is an example of the data: var data = { "cars" : 2 ...

Invoke index functions within a component

I have a widget/component written in Angular 4 within the index.html file. Before and after this angular app, there are various HTML elements due to the nature of it being an additional component for the website. The head section of the index file include ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

how to send both the useState setter and object as props to a child component in React using TypeScript

Having an issue with passing useState setter and object (both together) to the child component. Successfully passed the object by spreading it like this {...object}, but unsure of the syntax to pass the setter along as well. Here's a code example: < ...

Having trouble locating an Ionic module with your Ionic Web Builder?

Currently, I am working on building my Ionic app using their web build system. In my app.component.ts file, I have included the following import statement: import { File } from '@ionic-native/File/ngx'; Although this project compiles successful ...

Converting a JavaScript function to work in TypeScript: a step-by-step guide

When writing it like this, using the this keyword is not possible. LoadDrawing(drawing_name) { this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name); } LoadCB(drawing, drawing_name) { if (drawing == null) { return; ...

The routing navigate method is failing to direct to the desired component

For the past day, I have been struggling to find a solution to my issue but without success. The routing seems to be malfunctioning as it keeps showing the HTML content from app.component.html even when I try changing the path in the URL. Here is a snippe ...

Angular component template fails to recognize data that is clearly defined and present within the component

Here is a snippet of code from my component: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-home', templateUrl: './home.component. ...

When the boolean is initially set to false, it will return true in an if statement without using

My Angular component contains a component-level boolean variable and an onClick event. Here's what the HTML file looks like: <div class="divClass" (click)="onClick($event)"></div> The relevant code from the TypeScript file is as follows: ...

Capable of retrieving response data, however, the label remains invisible in the dropdown menu

Upon selecting a country, I expect the corresponding city from the database to be automatically displayed in the dropdown menu. While I was able to retrieve the state response (as seen in the console output), it is not appearing in the dropdown menu. Inte ...

Using TypeScript and HTML to toggle a switch and retrieve its value

I am currently trying to utilize a toggle switch to determine which methods need to be activated. My expectation is that I can obtain a Boolean value indicating whether the switch is turned on or off. However, I am unsure of how to retrieve this informatio ...

The absence of typings.json in Typescript is creating an issue

As of now, I am encountering the following error during compilation: typings.json is missing In my existing packages.json, I have included the following dependency: "devDependencies": { "typescript": "^2.6.1", ... } Do you have any suggestion ...

Creating a gradient background with the makeStyles function

Why is it that the background: 'linear-gradient(to right, blue.200, blue.700)' doesn't work within makeStyles? I just want to add a gradient background to the entire area. Do you think <Container className={classes.root}> should be rep ...

Utilize IntelliJ's TypeScript/JavaScript feature to extract a method from all instances

I am relatively new to using IntelliJ Idea Ultimate 2020 and I am currently exploring the refactoring functionalities within the software. Is there a way to extract a method from a section of code and apply it to all instances easily and exclusively withi ...

When the child component's form is marked as dirty, the parent component can access it

I have implemented a feature in my application that notifies users about pending changes on a form before they navigate away. Everything works as expected, but I have a child component with its own form that needs to be accessed by the guard to check if i ...

JavaScript: Leveraging arrays as key values

Is there a way in javascript to create an Object with keys as numbers and values as arrays of objects? I am aiming to generate an object structured like this: {Key: "1", value: [Object, Object, ...], key: "2", value: [Object, Object, ...], key:"N", value ...

Is the spread operator in React failing to function as anticipated?

In my current project, I encountered an issue while trying to pass a GeolocationCoordinates object to a child component using the spread operator. Strangely, in the child props, it appears as an empty object: interface HUDState { geoCoords: Geolocation ...