What could be causing the issue with typing into the Formik and Yup input fields?

Whenever I attempt to enter text into the input fields, no characters show up. Strangely, a similar login page using the same code is functioning perfectly fine. At this moment, I'm baffled as to why it isn't working on this specific one. My suspicion was that the issue might be related to how I defined the initialValues since they are nested, but even after trying to rewrite them without nesting, the issue persists.

import { NextPage } from 'next'
import { Prisma } from '@prisma/client';
import { FormikValues, useFormik, validateYupSchema } from 'formik';
import * as Yup from 'yup'
import { useState } from 'react';
import { useRouter } from 'next/router';
import { useSession } from 'next-auth/react';

const Register: NextPage = () => {

  const router = useRouter()
  const { data: session } = useSession()
  if (session) {
    router.push('/')
  }

  const [error, setError] = useState('')

  const handleRegister = async ({
    userInfo: {
      email,
      password
    },

    companyInfo: {
      companyName,
      gender,
      firstName,
      lastName,
      street,
      houseNumber,
      postcode,
      city,
      country,
      countryCode,
      callNumber,
      emailAddress,
      website,
      socials
    } }: FormikValues) => {

    const userInfo: Prisma.UserCreateInput = {
      email,
      hashedPassword: password //Not hashed yet!
    }

    const companyInfo: Prisma.CompanyCreateInput = {
      name: companyName,
      gender,
      firstName,
      lastName,
      street,
      houseNumber,
      postcode,
      city,
      country,
      countryCode,
      callNumber,
      emailAddress,
      website,
      socials,
      companyUser: {
        connect: { id: '' }
      }
    }

    const registerData: FormikValues = {
      userInfo,
      companyInfo
    }

    const registerDataJSON = JSON.stringify(registerData)

    const endpoint: RequestInfo = '/api/register/register'
    const options: RequestInit = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: registerDataJSON
    }

    try {
      const response: Response = await fetch(endpoint, options)

      const url = response.headers.get('Location')

      if (url) {
        window.location.href = url
      }
    } catch {
      setError('Register failed')
    } finally {
      formik.setSubmitting(false)
    }
  }

  const formik = useFormik({
    initialValues: {
      userInfo: {
        email: '',
        password: ''
      },

      companyInfo: {
        companyName: '',
        gender: '',
        firstName: '',
        lastName: '',
        street: '',
        houseNumber: '',
        postcode: '',
        city: '',
        country: '',
        countryCode: '',
        callNumber: '',
        emailAddress: '',
        website: '',
        socials: ''
      }
    },
    validationSchema: Yup.object().shape({
      userInfo: Yup.object().shape({
        email: Yup.string()
          .required('email address is required')
          .email('email address must be valid')
          .transform((value) => value.replace(/\s+/g, ' ').trim())
          .trim('Email Address cannot include leading and trailing spaces'),
        password: Yup.string()
          .required('Password address is required')
          .min(8, 'Password must be at least 8 characters long')
          .max(20, 'Password cannot be longer than 20 characters')
          .matches(
            /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&*])/,
            'Password must contain at least one number as well as one uppercase, lowercase and special character'
          )
          .trim('Password cannot include leading and trailing spaces')
          .matches(
            /^(?!.* )/,
            'Password cannot contain whitespaces'
          )
      }),
      ...
    }),
    onSubmit: (values) => {
      handleRegister(values)
    }
  })

  return (
    <form onSubmit={formik.handleSubmit} noValidate>
      <h2>User Information</h2>

      <label>
        Email Address<span>*</span>
        <input
          name='email'
          type='email'
          value={formik.values.userInfo.email}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
        />
      </label>
      ...       
    </form>
  )
}

export default Register

Answer №1

If you have nested initial values, it is important that the input name reflects the corresponding object property. In your specific case, you need to modify the current input name ('email') to 'userInfo.email' as illustrated below:

<input
  name="userInfo.email"
  type="email"
  value={formik.values.userInfo.email}
  onChange={formik.handleChange}
  onBlur={formik.handleBlur}
/>

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

Leveraging the power of the map function to manipulate data retrieved

I am working on a nextjs app that uses typescript and a Strapi backend with graphql. My goal is to fetch the graphql data from strapi and display it in the react app, specifically a list of font names. In my react code, I have a query that works in the p ...

What could be causing my HTML source code to display incorrectly when using getStaticProps and getServerSideProps?

Encountering issues with the HTML rendering of a page using getStaticProps or getServerSideProps. No content related to the <head> element or main content like <h1> and <p> tags. For example: Visit this link => When inspecting the pa ...

Helping to maintain compatibility with previous URL structures using Next.js

Exploring a new Next.js project, I find myself in a situation where I must support legacy URLs without the ability to implement 301 redirects. The URLs I need to accommodate look like www.dan.com/foo/bar/slug As of now, my folder structure is arranged as ...

Design a unique <Link> component within my React shared UI library by utilizing a monorepo approach

As a newcomer to application architecture, I am eager to experiment with building an app using a Monorepo structure. I have a query regarding a Next.js frontend app that utilizes my React-based UI package shared across multiple apps within the same Monore ...

Sharing state between two functions in React using Hooks

Coming from a background in Vue, I am struggling to comprehend how to conditionally show something when the HTML is fragmented into different parts. Imagine having this structure: import React, { useState } from "react"; const [mobileNavOpen, setMobi ...

costly API request within the server component for Next.js 13

I am currently working with a server component that looks like this: const ContentSubmissions = async () => { const blogsData: any = await getBlogsData(); const galleryData: any = await getGalleryData(); const questionsData: any = await getQuestio ...

Issues with the inheritance functionality in styled components are causing errors

The issue arises when I try to customize the styling of my PrimaryButton component, separate from the DefaultButton. Despite writing style properties for it, the changes do not take effect. Here is the folder structure: https://i.stack.imgur.com/0KjyH.pn ...

Oops! The requested page "/api/auth/[...nextauth]" is missing the necessary "generateStaticParams()" function, thus making it incompatible with the "output: export" configuration

Currently, I am working on a Next.js project where I have successfully implemented user authentication using next-auth with the Google Provider. However, while attempting to build the project, an error is being thrown by the compiler stating: "Error: Page ...

Leverage the power of NextJS App Router to effortlessly redirect all routes to two nested dynamic routes at the

Seeking assistance with understanding the intricacies of the app router, particularly when dealing with deeply nested dynamic routes. Imagine running an ecommerce platform with multiple stores offering various shopping modes like pickup and delivery. How ...

Apologies, we were unable to establish a connection as the server refused to respond on the specified IP address and port

kubectl get namespace default Active 3h33m ingress-nginx Active 3h11m kube-node-lease Active 3h33m kube-public Active 3h33m kube-system Active 3h33m kubectl get services -n ingress-nginx NAME ...

Precise loading display in React using splines

When utilizing next.js to render a spline model, I have encountered an issue where the "onLoad" function does not accurately reflect the loading time. import Spline from '@splinetool/react-spline'; import { useState } fr ...

The error message "window is not defined" is commonly encountered in Next

Having some trouble with using apexcharts in a next.js application, as it's giving me an error saying 'window is not defined'. If anyone has any insights or solutions, I would greatly appreciate the help. Any ideas on what could be causing ...

The issue of not displaying the Favicon in Next.js is a common problem

I am currently using Next.js version 13.4.7 with the App directory and I am facing an issue with displaying the favicon. Even though the favicon image is located in the public folder and in jpg format, it is not being displayed on the webpage. However, w ...

Tips for streamlining responses for the latest create-next-app version

After running npx create-next-app@latest, a series of questions are prompted that disrupt our docker pipeline automation. Is there a way to automate the response to these questions? Currently, we have this command in our Dockerfile: RUN npx --yes create- ...

Using the onClick event to dynamically alter the class name within a mapped array by leveraging Hooks

I'm currently working on developing an answer sheet, commonly known as a "Bubble sheet", where the user has the ability to select either "A,B,C, or D" and see the bubble transition from light mode to dark mode just like when marking with a physical pe ...

Error: WebAssembly.instantiate() encountered a TypeError when trying to import module #0 named "env". The error indicates that the module is not a valid object or

We are currently involved in a project utilizing Next.js and Three.js (react-three-fiber). However, after clearing the cache in the browser, the 3D model disappeared and we encountered some errors. Specifically, there was one warning and one error that kep ...

Using Material UI in a NextJS app causes issues when the app is deployed

After developing a NextJS application that utilizes server-side rendering and Material UI, I encountered some issues when deploying it in production mode. While everything worked smoothly during development, certain features stopped functioning correctly o ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

Importing Heroicons dynamically in Next.js for more flexibility

In my Next.js project, I decided to use heroicons but faced a challenge with dynamic imports. The current version does not support passing the icon name directly to the component, so I created my own workaround. // HeroIcon.tsx import * as SolidIcons from ...

Assembly Unsuccessful: Program "npm install" completed with error code 1

Ever since the project began, deploying has always been smooth sailing. However, today out of the blue, this perplexing message started popping up on Vercel... The application was developed using Next.js I scoured high and low for a solution that would w ...