Invalid object error in react when submitting form

Viewed 99

I entered some special character in password field. And i'm getting invalid object error when submitting the form. How can i handle such type of error?

Consider this react code:

import React,{useState} from 'react'
import {useParams} from 'react-router-dom'
import axios from 'axios'

function ResetPassword(props) {

    const { id } = useParams()

    const [forgot,setForgot]=useState(
        {
            token:id?id:null,
            password:null,
            email:null
        }
        )
    const [error,setError]=useState('');
    console.log(forgot)

    const submitHandler=(e)=>{
        e.preventDefault()

            
        axios.post('/reset-password',forgot)
        .then(response=>{
            console.log(response)
            response.data.status? props.history.push('/login'):''
        })
        .catch(error=>{
            setError(error.response.data.msg)
        })
      
        // console.log(forgot);
    }



    return (
        <div class="container-md bg-light mt-5 p-5 col-lg-4">
            <form onSubmit={e=>submitHandler(e)}>
                <h1 class='mb-5 text-center'>Reset Password</h1>
                {error && <p className="alert alert-danger">{error}</p>}
                <div class="mb-3">
                    <label for="exampleInputPassword1" class="form-label">Token</label>
                    <input type="text" value={forgot.token} class="form-control" id="exampleInputPassword1" 
                    onChange={e=>setForgot({...forgot,token:e.target.value,})}
                    required />
                </div>
                <div class="mb-3">
                    <label for="exampleInputPassword1" class="form-label">Email</label>
                    <input type="email" class="form-control" id="exampleInputPassword1" 
                    onChange={e=>setForgot({...forgot,email:e.target.value,})}
                    required />
                </div>
                <div class="mb-3">
                    <label for="exampleInputPassword1" class="form-label">New Password</label>
                    <input type="password" class="form-control" id="exampleInputPassword1" 
                    onChange={e=>setForgot({...forgot,password:escape(e.target.value)})}
                    required />
                </div>
                <div class="mb-3">
                    <label for="exampleInputPassword1" class="form-label">Confirm Password</label>
                    <input type="password" class="form-control" id="exampleInputPassword1" 
                    onChange={e=>setForgot({...forgot,password_confirmation:escape(e.target.value)})}
                    required />
                </div>
                <div className="d-flex flex-column">
                    <button type="submit" class="btn btn-success flex-grow-1">Update</button>
                </div>
            </form>
        </div>
    )
}

export default ResetPassword

In case of normal value in password field no issue arrive but when i'm trying to enter special character it's throwing invalid object error.

Trying to enter this type of password value:

{token: "54550", password: "/85236", email: "a@b", password_confirmation: "*96325"}
2 Answers

You can choose to save the first error into state and render, but in cases like this with multiple unmet password requirements you may want to actually render all errors in a list.

{error && [error].flatMap(err => (
  <p key={err} className="alert alert-danger">{error}</p>
))}

How it works:

[error].flatMap()

If error is a string value it will be placed into an array and mapped. If error is an array of strings, it will be flattened be an array of strings (not an array of an array of strings) and mapped.

const mapErrors = arg => [arg].flatMap(el => el).join(', ');

console.log(mapErrors('error'));
console.log(mapErrors(['error 1', 'error 2', 'error 3']));

Because error.response.data.msg return an object so when you use {error && <p className="alert alert-danger">{error}</p>}, it will show this error.

You need to make sure pass a string value when call setError, example:

setError(error.response.data.msg?.password[0])
Related