Sanjana
Sanjana

Reputation: 296

How to find display error message from API in reactjs

I'm new to React.JS, creating an app for contacts. From API, the fields of contact got validated, if same name or phone number exists then it will show error message in API. My query is how to show the error message in UI while entering the same name or phone number. Do I need to fetch from Contact API? If yes, I could fetch the API of contacts in DIdmount but don't know how to show the error? Can any one help me in this?

Upvotes: 7

Views: 25913

Answers (3)

Hammad ul Hasan
Hammad ul Hasan

Reputation: 314

Yes if you want exact error message from api response than you can get this by .then(responseJson=> { console.log(responseJson.response.data.message) })

Upvotes: 1

VnoitKumar
VnoitKumar

Reputation: 1426

Have an API to check if the name is available or not, and hit the API when the user changes something in the input.

import React, { useState } from "react";
import ReactDOM from "react-dom";

let delayTimer;

function App() {
  const [name, setName] = useState("");
  const [nameAvailable, setNameAvailable] = useState(null);

  async function checkNameAvailable() {
    try {
      const response = await APIUtility.isNameAvailable(name);

      const { data = null } = response;
      if (data) {
        setNameAvailable(data); // data may be true or false
      }
    } catch (error) {
      setNameAvailable(null);
    }
  }

  function handleNameChange(e) {
    setName(e.target.value);
    if (name.length > 0) {
      if (delayTimer) clearTimeout(delayTimer);
      delayTimer = setTimeout(function() {
        checkNameAvailable();
      }, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
    }
  }

  return (
    <form>
      <label htmlFor="invite_code">Enter your name:</label>
      <input
        value={name}
        onChange={handleNameChange}
        type="text"
        name="inviteCode"
        id="invite_code"
        autoComplete="off"
      />
      {nameAvailable && <span>Name already taken</span>}
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 0

LydiaHendriks
LydiaHendriks

Reputation: 1600

Create a state variable for error with the initial value set to "" or null. Make the api call, the server (assuming you are also building the server) should check to see if the name and phone number already exist. If they already exist the server should return an error. In your react app catch the error after your API call and assign it to your state variable for error. Here is an example for the client using hooks.

export default function RegistrationForm(props) {
    const [error, setError] = useState(null)
    const errorDiv = error 
        ? <div className="error">
            <i class="material-icons error-icon">error_outline</i>
            {error}
          </div> 
        : '';

    const handleSubmit = e => {
        e.preventDefault();
        setError(null);
        
        const { full_name, user_name, password } = e.target;

        AuthApiService.postUser({
            full_name: full_name.value, 
            user_name: user_name.value, 
            password: password.value
        })
            .then(user => {
                full_name.value = '';
                user_name.value = '';
                password.value = '';
                props.onRegistrationSuccess();
            })
            .catch(res => {
                setError(res.error);
            })
    };

    return(
        <form className='RegistrationForm'
            onSubmit={handleSubmit}
        >  
            <div className='full_name'>
                <label htmlFor='RegistrationForm__full_name'>
                    Full name
                </label>
                <Input
                    name='full_name'
                    type='text'
                    required
                    id='RegistrationForm__full_name'>
                </Input>
            </div>
            <div className='user_name'>
                <label htmlFor='RegistrationForm__user_name'>
                    User name
                </label>
                <Input
                    name='user_name'
                    type='text'
                    required
                    id='RegistrationForm__user_name'>
                </Input>
            </div>
            <div className='password'>
                <label htmlFor='RegistrationForm__password'>
                    Password
                </label>
                <Input
                    name='password'
                    type='password'
                    required
                    id='RegistrationForm__password'
                    >
                </Input>
            </div>
            <div className='confirm-password'>
                <label htmlFor="LoginForm__confirm-password">
                    Retype Password
                </label>
                <Input
                    name='confirm-password'
                    type="password"
                    required
                    id="LoginForm__confirm-password">
                </Input>
            </div>
            {errorDiv}
            <Button type='submit' variant='contained' color='default'>
                Register
            </Button>
        </form>
    )
}

Upvotes: 3

Related Questions