Home > Mobile >  How to make API call to login
How to make API call to login

Time:10-15

I am using MediaWiki as my backend and I have it running on 'localhost/name'.

My goal now is to develop the front end using React JS (in which I have no experience). Using the MediaWiki API documentation, I have created in my react project the file api.js.

I stored api.js under .src/api and this is the file content.

var WMAPI = {
    getToken: function(username, password) {
        fetch('http://localhost/wikimedia/api.php', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'text/plain'
            },
            body:'action=login&lgname=' username '&lgpassword=' password '&format=json'
        })
        .then((response) => response.json())
        .then((response) => {
            WMAPI.login(response.login.token, username, password);
            console.log('response >>', response.login)
        }).done();
    },

    login: function(val, username, password) {
        fetch('http://localhost/wikimedia/api.php', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'text/plain'
            },
            body: 'action=login&lgname=' username '&lgpassword=' password '&lgtoken' mytoken '&format=json'
        })
        .then((response) => response.json())
        .then((response) => {

            console.log('Success >>', response.login);
        }).done();
    }
}

modules.exports = WMAPI;

Next, I created a login page under .src/pages/login.js.

import React from 'react';

const Login = () => {
    return (
        <div className="form">
            <h1>Login Page</h1>
            <form>
            <div className="input-container">
                <label>Username </label>
                <input type="text" name="uname" required />
            </div>
            <div className="input-container">
                <label>Password </label>
                <input type="password" name="pass" required />
            </div>
            <div className="button-container">
                <input type="submit" value="Login" />
            </div>
            </form>
    </div>
    );
};
export default Login;

I think I have set up everything I needed, but now I'm lost. I've been reading this for some time, but I can't understand how to implement it in my case.

Can anyone give some light on this issue?

CodePudding user response:

Kind of a big question, almost as big as "build my app for me". Check out https://stackoverflow.com/help/how-to-ask

But from a high level you want to connect the input values to react state. The documentation link you've posted describes how to do that. Maybe just try console.logging the state values in response to input changes first to make sure you have the inputs wired up correctly.

Once you have the input values available on state, you'll probably want to call the getToken method using the username and password. The react documentation on events describes how to do things in response to events such like button clicks or form submissions. https://reactjs.org/docs/handling-events.html

My assumption is that after calling getToken, you'd then want to log in using the retrieved token. So call that method using the username, password, and token.

You'll probably need a basic understanding of javascript promises to understand how to order the calls, ie only call login AFTER getting a response from getToken

https://web.dev/promises/ https://javascript.info/promise-basics https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

So 3 main steps:

  1. Connect form to state
  2. When form is submitted, make call to getToken, passing username and password (which you have from step 1)
  3. After you get a response from getToken make a new call to login, passing username, password and token (which you get from step 2)

Is there a more specific aspect you need help with?

CodePudding user response:

I would just use states to handle transferring the username and password data. I've added working code below. The doSomethingWithCreds function can be used to transfer your data to some route and eventually tie a token to it.

I highly recommend you take the time to learn states and about some of the general hooks like useRef and useEffect. It will make developing and understanding some of the key topics in react much easier.

If you have any questions feel free to comment and i'll do my best to respond.

State Doc Reference

import {useEffect, useState} from 'react'
import './App.css';

function App() {

  const[pass,setPass] = useState()
  const[user,setUser] = useState()

  const handlePassChange = event =>{//Updates pass every time a new char is entered instead of on submit
    setPass(event.target.value)
  }

  const handleUserChange = event =>{
    setUser(event.target.value)
  }
  
  const doSomethingWithCreds = () =>{
    console.log('password: '   pass)
    console.log('user'   user)
  }

  return (
    <div className="form">
      <h1>Login Page</h1>
      <form>
        <div className="input-container">
            <label>Username </label>
            <input onChange={handleUserChange} type="text" name="uname" required />
        </div>
        <div className="input-container">
            <label>Password </label>
            <input onChange={handlePassChange} type="password" name="pass" required />
        </div>
        <div className="button-container">
            <input onClick={doSomethingWithCreds} type="submit" value="Login" />
        </div>
      </form>
    </div>
  );
}

export default App;
  • Related