Home > database >  how to catch api resonse data in react js
how to catch api resonse data in react js

Time:10-17

i have one project in spring boot where i have created one API login.where i am sending user name and password with this API .if data is present in database it is returning login successfully if not then it is returning login fail.in react i have to text filed and i am storing that data.now i want to call login API in react with saved text field value and if login successfully then i want to save that response or that returned value in react it may be login successfully or all user details or show that response in react.please anyone help

CodePudding user response:

Use Error handling function

try{
//Call your API here
}
catch(){
//Error handles here
}
finally{
//Executes anyway
}

CodePudding user response:

You have to save your response in state then show it on frontend

import axios from 'axios';
const [loginData, setLoginData] = useState([]);
const onSubmit = async (e) => {
    e.preventDefault();
    try {

        const requestBody = {
            emailAddress: email,
            password: password,
        }

        axios.post(`${config.url.API_URL}${BASE_URL.Auth_BASE_URL}/login`, requestBody)
            .then(response => {
                if (response) {
                    setLoginData(response);
                    console.log("Login success");

                } else {
                    console.error("Login fail");
                }

            }).catch(function (error) {
           console.log(error);
        });
    } catch (err) {

        console.log(err);
    }
}
  • Related