Issue with React TypeScript occurring upon the second submission of a form

After successfully submitting a form for the first time, I encounter an error upon refreshing the page

import { Link } from 'react-router-dom'
import { PrismaClient, Prisma } from '@prisma/client'
import './Register.css'

const Register = () => {
    const registerForm = document.querySelector('.register-form') as HTMLFormElement
    const prisma = new PrismaClient()

    interface User{
        firstname: string
        email: string
        password: string
    }

    function registerNewUser(userData: User) {
        // const createUser = await prisma.user.create({
        //     data: {
        //         name: userData.firstname,
        //         email: userData.email,
        //         password: userData.password
        //     }
        // })
        console.log(userData)
    }

    return <div className="register-card" id='form'>
    <h2>Register</h2>
    <form className="register-form">
        <input type="text" name="firstname" placeholder="firstname"/>
        <input type="text" name="email" placeholder="email"/>
        <input type="password" name="password" placeholder="password"/>
        <button onClick={(e) => {
            e.preventDefault()
            const firstname: string = registerForm.firstname.value
            const email: string = registerForm.email.value
            const password: string = registerForm.password.value

            const newUser: User = {
                firstname: firstname,
                email: email,
                password: password
            }

            registerNewUser(newUser)
        }}>Register</button>
    </form>
    <Link to="/"><p>I have an account</p></Link>
</div>;
}
 
export default Register;

Attempts to make the registerNewUser function async didn't resolve the issue. My expectation is that registerNewUser should work and output 'userData' in the console

Answer №1

Aha! I've identified the issue, simply had to relocate the form declaration inside the onClick function

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

Exploring the process of integrating types into a GraphQL schema with the use of React and TypeScript

I am facing a challenge with my query, which is structured like this: query MyQuery($id: ID!) { something(id: $id) { details { id name } } } In the types.graphql file, I have the following definitions: type ...

Setting default parameters for TypeScript generics

Let's say I define a function like this: const myFunc = <T, > (data: T) => { return data?.map((d) => ({name: d.name}) } The TypeScript compiler throws an error saying: Property 'name' does not exist on type 'T', whic ...

Utilizing ng-class to apply separate conditions to an array of buttons in Angular

I am facing a straightforward issue. I need to create an array of 3 buttons, and upon clicking each button, the background color of the page should change. The catch is that I have to achieve this using pure Angular-TypeScript without the use of JavaScript ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Utilize Firebase for Playwright to efficiently implement 'State Reuse' and 'Authentication Reuse'

In my testing environment, I want to eliminate the need for repeated login actions in each test run. My approach involves implementing 'Re-use state' and 'Re-use Authentication', but I've encountered a challenge with Firebase using ...

How can we stop the parent modal from closing if the child component is not valid?

I have a main component with a modal component that takes another component as a parameter. The child modal component has some logic where I need to check if the child component is valid before closing the modal. const MainComponent: FC<IProps> => ...

Extracting data from the Sanity API response in JSON format using Typescript

Struggling with extracting information from a Sanity Client API call and decoding the resulting JSON data. Can someone guide me on how to access specific values? Below is the output of the API call: [ { slug: { current: "test-post", _type: ...

The requested resource could not be located at @angular/platform-browser.js

I am attempting to set up ASP.NET MVC 5 (not Core) + Angular 2.0.0 + JSPM + SystemJS + TS Loader. Upon running the application, I encounter the following error: Failed to load resource: the server responded with a status of 404 (Not Found) http://localho ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

challenges with template inheritance: when one template takes precedence over another

I have encountered an issue with my two HTML templates, login.html and signup.html. Both of these files inherit from the base.html file, but there seems to be a problem where one file is overriding the title and content of the other. So when I visit /login ...

Steps to troubleshoot TypeScript NS_BINDING_ABORTED error when making POST requests

Recently, I implemented a basic functionality in my project that sends a POST-request to the backend using a common wrapper function. This function utilizes 'fetch' and is called within an async/await context. The body of the request consists of ...

Exploring/Adjusting an RxJS Observable Object

I'm currently working with a typescript method that looks like this: private processRequest<T>(request: Observable<T>, ...): Promise<T> {...} request is an HttpClient Observable processRequest(httpClient.get(url, ...)); ... processR ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...

Using TypeScript to incorporate JS web assembly into your project

I have been attempting to incorporate wasm-clingo into my TypeScript React project. I tried creating my own .d.ts file for the project: // wasm-clingo.d.ts declare module 'wasm-clingo' { export const Module: any; } and importing it like this: ...

What is the best way to display information in a Handlebars template file?

Having trouble displaying data in the template using NestJS with mysql. Here is the code snippet from controller.ts: import { Controller, Get, Post, Put, Delete, Body, Param, Render, UsePipes, Logger, UseGuards} from '@nestjs/common'; import { P ...

Expanding a Typescript generic class by adding abstract methods

Struggling to expand an abstract generic class and encountering issues with extending certain methods. Take a look at this: abstract class A<T,K> { protected abstract upload<S>(item: T): S protected abstract download(item: T): K } ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

What is causing this error? The length of this line is 118 characters, which exceeds the maximum allowed limit of 80 characters for max-len

I am encountering issues while attempting to upload my function to Firebase, specifically receiving two errors as follows: 39:1 error This line has a length of 123. Maximum allowed is 80 max-len 39:111 warning 'context' is defined but ...

Tips for utilizing field mapping for a nested item in TypeScript

I am working with two separate objects below, let response = { offer: { custom_fields: { job_title: 'engineer' }, starts_at: 'test', ...