Validating image uploads using Yup and Formik in a standalone module

I am facing an issue in my Next.js application where I am attempting to validate the upload of an image using Formik and Yup by passing a method called handleOnImageChange in the component. However, I am struggling to make it work this way. I have also tried using useFormikContext but to no avail. Can someone provide assistance?

 const validationSchema = yup.object().shape({
        file: yup.mixed().required('Please upload an image')
    });

 function handleOnImageChange(event) {
      const file = event.currentTarget.files[0];
      uploadImage(file);
  }

<Formik
  onSubmit={handleSubmit}
  initialValues={defaultFormState}
  validationSchema={validationSchema}
>
  {() => (
    <>
    <div>
     <Uploader imageSrc={imageSrc} handleOnImageChange={handleOnImageChange} />
     <ErrorMessage
       name="file"
       component={InputError}
      />
    </div>
    </>
  )}
</Formik>

Using the uploader component:

const Uploader = ({handleOnImageChange, imageSrc}) => {
  return (
    <>
      <input id="file" accept=".jpg, .jpeg, .png, .gif, .webp" name="file" type="file" onChange={handleOnImageChange} />
      {imageSrc && (
        <img src={imageSrc} width="200"/>
      )}
    </>
  )
}

Answer №1

In order to validate, you must set Formik values first. Within the handleOnImageChange function, the upload image function is being called which uploads an image through an API endpoint and returns a URL in response. To make this function asynchronous, await the response and then set the Formik state. Here is a sample code:

const validationSchema = yup.object().shape({
        file: yup.mixed().required('Please upload an image')
    });

 async function handleOnImageChange(event,formik) {
      const file = event.currentTarget.files[0];
     let res = await uploadImage(file);
let url =res.data.url // depends on your API response
formik.setFieldValue("file",url)//"file indicates your state or formik value

  }

<Formik
  onSubmit={handleSubmit}
  initialValues={defaultFormState}
  validationSchema={validationSchema}
>
  {(formik) => (
    <>
    <div>
     <Uploader imageSrc={formik.values.file} handleOnImageChange={(e)=>handleOnImageChange(e,formik)} />
     <ErrorMessage
       name="file"
       component={InputError}
      />
    </div>
    </>
  )}
</Formik>

It is important to check for null or undefined in case the file is not selected by the user and a null object is returned when the user opens the file input but cancels file selection.

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

Error occurs when attempting to clear the cache storage

useEffect(async () => { caches.open('my-cache') }, [token, user_id]) Upon trying to log out of the application, const logoutFunc = () => { localStorage.clear() caches.keys().then((list) => list.map((key) => { ...

Error encountered in Webpack 5 module federation when attempting to dynamically load a remote module and a

I am attempting to transform a large monolithic React application into micro-frontends using webpack module federation. The remote module has already been deployed and is functioning flawlessly when the dev server is running locally. However, upon running ...

What could be causing a hydration error when utilizing a table in Next.js?

When attempting to use the tr tag in my code, I encountered an error message that reads: Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. import React from 'react' import {useS ...

Establish the default sorting for Material UI tables

I'm struggling with setting the default sorting for a Material UI table. Is there a more straightforward way to do this without using a button at the top? I want the table to automatically sort by protein when it is loaded. import * as React from &apo ...

The documentation for the 4-11.4 version of Material UI cannot be found anywhere

After the release of MUI v5.0.0-rc.1, it appears that all documentation pages for version 4, except for v4.12.3, have vanished. https://mui.com/versions/ Furthermore, (currently not accessible) Is there a way to access previous versions' document ...

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...

Discontinuing the mobx autorun feature upon componentWillUnmount

In my componentDidMount, I have the following autorun function: componentDidMount() { this.autoUpdate = autorun(() => { this.setState({ rows: generateRows(this.props.data) }) }) } Unfortunate ...

Updating the display in React Native

My application receives its theme (colors and styles) from a REST API. Whenever there is a change in the theme on the server, the app is notified through socket communication so that it can fetch the new theme using REST. The theme is retrieved in a Redux ...

Troubleshooting a Next.js background image problem when hosting on Netlify

I've encountered an issue while attempting to deploy a nextjs website on Netlify. Everything works perfectly on my local server, but once it's on Netlify, the background image URL changes and the image becomes invisible. Original CSS code: backg ...

"Enhance your software with a customizable interface or develop new functionalities to generate analogous

Having API data with a similar structure, I am looking to streamline my code by filtering it through a function. However, as someone new to TypeScript, I am struggling to implement this correctly using a function and an interface. Essentially, I aim to ach ...

When the parent component in React JS rerenders, the props are not automatically passed down to the child

I have come across similar questions in the past, but I have not found any answers that directly address the issue I am facing in my scenario. In my case, there is a parent component that passes a property to a child component's state. Depending on t ...

Adjust the dimensions of the icon

My current project involves creating a sidebar with icons and associated text to represent each icon. However, I encountered an issue while trying to adjust the size of the icons within the sidebar using the "useStyles()" method. For some reason, the size ...

Unable to locate the Next Js context

import { createContext, ReactNode, useState } from 'react'; import { MenuItem } from '../interfaces/menu.interfaces'; import { TopLevelCategory } from '../interfaces/page.interface'; export interface IAppContext { menu: M ...

Tips on fixing server/client content mismatch caused by browser auto translate

While constructing a website with next14, storyblok, and i18n, I encountered an issue in the browser related to the automatic Google translate feature for Georgian and English languages. Despite setting Georgian as the default language in my app, when swit ...

Managing data flow in React and Reflux: Utilizing a single component duplicated in the DOM

Imagine this Tree scenario: <Homepage> <HeaderSection> <Navbar> <ShoppingCartComponent> </Navbar> </HeaderSection> <MainContent> <ShoppingCartComponent> &l ...

encountering an issue with server-side rendering of React causing an error

Node.js has been a bit of a challenge for me, especially when it comes to working with react and express. I have been struggling to find comprehensive tutorials and troubleshooting resources, leading me to ask minimal questions in the correct manner. While ...

Displaying Material UI Styles: A Challenge

Currently working on a website using Material-UI and React. Strangely, the styling applied through Material-UI's Hook API functions perfectly on codesandbox.io but fails to work when running locally. Notably, the border radius feature fails to update ...

Having trouble getting the @tailwindcss/forms plugin to function properly alongside React

After installing the tailwindcss plugin forms using npm with npm install @tailwindcss/forms, I added the dependency in the forms section of my tailwindconfig file by including plugins: [ require("@tailwindcss/forms") ]. As per the documentation ...

Upon launching a fresh project with Next.js 13, three errors are immediately encountered

Working with a technology in beta for the first time is throwing some errors my way. Should I just overlook them since it's expected, especially considering that I'm new to Next.js? To kick off my app development, I used npx create-next-app@late ...

Encountering an error in React when attempting to convert a class component to a function

As I've been converting my class components to functions, I encountered a hook error related to my export default. Although I believe it's a simple issue, I can't seem to find the solution I need. The following code is where the error occur ...