skip to Main Content

I am trying to create a login form in react.js. I have an API where there is only username and password. Now I don’t know how to call an Api in React.js. I have watched tutorials but I didn’t get it. I am not a react developer I am just a beginner. One of my friend helped me and he called the API using JavaScript, but I am trying to write the code with the help of YouTube and chatGpt, still I am getting errors. Below is the JavaScript code which is working.

Now I want to write same code in react that my friend has written in JavaScript. I can write html and CSS but I cannot write JavaScript and its libraries.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>

    <div class="flex flex-col items-center justify-center min-h-screen bg-gray-100 py-2 sm:px-6 lg:px-8">
        <div class="max-w-md w-full space-y-8">
          <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">
            Login Form
          </h2>
          <form id="loginForm" class="mt-8 space-y-6">
            <div>
              <label for="username" class="sr-only">Username:</label>
              <input type="text" id="username" name="username" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Username">
            </div>
            <div>
              <label for="password" class="sr-only">Password:</label>
              <input type="password" id="password" name="password" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Password">
            </div>
            <button type="submit" class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
              Login
            </button>
          </form>
          <p id="message" class="mt-2 text-center text-sm text-gray-600"></p>
        </div>
      </div>
      

<script>
    $(document).ready(function() {
      $('#loginForm').submit(function(event) {
        event.preventDefault(); // Prevent the form from submitting normally
        
        // Get username and password from the form
        var username = $('#username').val();
        var password = $('#password').val();
        
        // Construct the URL with concatenated login and passw parameters
        var apiUrl = 'http://portal.mashitec.com/SalesWebApi/api/User1/?login=' + encodeURIComponent(username) + '&passw=' + encodeURIComponent(password);
        
        // Make POST request to API
        $.ajax({
          type: 'POST',
          url: apiUrl,
          success: function(response) {
            // Check if the response matches the username
            if (response === username) {
              $('#message').text('Authorized');
            } else {
              $('#message').text('Not Authorized');
            }
          },
          error: function(xhr, status, error) {
            $('#message').text('Error: ' + error);
          }
        });
      });
    });
</script>       

</body>
</html>

2

Answers


  1. It’s a good practice to create a specific file that handles API calls. This can help keep your codebase clean and makes it easier to manage all API-related operations in one place. Create a file named api.js in your src directory:

    // src/api.js
    
    import axios from 'axios';
    
    const API_BASE_URL = 'https://api.yourdomain.com';
    
    const instance = axios.create({
      baseURL: API_BASE_URL,
      timeout: 1000,
    });
    
    // You can add common headers or auth tokens here
    instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
    
    export const fetchData = async () => {
      try {
        const response = await instance.get('/endpoint');
        return response.data;
      } catch (error) {
        console.error('Error fetching data: ', error);
        // Handle errors here or throw them to be handled where the function is called
        throw error;
      }
    };
    

    Making an API Call from a React Component

    Now you can use the fetchData function from the api.js in any React component. Here’s an example:

    // src/App.js
    
    import React, { useEffect, useState } from 'react';
    import { fetchData } from './api';
    
    function App() {
      const [data, setData] = useState(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
    
      useEffect(() => {
        fetchData()
          .then(data => {
            setData(data);
            setLoading(false);
          })
          .catch(err => {
            setError(err);
            setLoading(false);
          });
      }, []);
    
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error loading data!</p>;
    
      return (
        <div>
          <h1>Data Loaded</h1>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      );
    }
    
    export default App;
    

    Handling Errors

    As shown in the component above, error handling is crucial when making API calls. You can handle errors within the API call function, or directly within the component, depending on how you prefer to manage error states in your application.

    Login or Signup to reply.
  2. Assuming that you have basic knowledge of React and how the states work.

    import React, { useState } from 'react';
    import axios from 'axios';
    
    const Page = () => {
      const [name, setName] = useState('');
      const [password, setPassword] = useState('');
    
    
      const handleSubmit = async (event) => {
        event.preventDefault();
    
        try {
          const response = await axios.post('/api', {
            name,
            password,
          });
          console.log('Login successful:', response.data);
        } catch (error) {
          console.error('Login error:', error);
        }
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <div>
            <label htmlFor="name">Name:</label>
            <input
              type="text"
              id="name"
              value={name}
              onChange={(event) => setName(event.target.value)}
            />
          </div>
          <div>
            <label htmlFor="password">Password:</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
            />
          </div>
          <button type="submit" onClick = {handleSubmit}>Login</button>
        </form>
      );
    };
    
    export default Page;
    

    This is the basic API call using Axios by taking the user input and sending it as payload.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search