Home > Blockchain >  weird issue with login?
weird issue with login?

Time:06-13

I have a small issue. Basically I have a login/register system built in React. This is how I handle the signup:

const submitHandler = async (data: object) => {
    console.log(data);
    await fetch("http://localhost:4000/signup", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.status_code === "SUCCESS") {
          router.push("/login");
        }
      })
      .catch((err) => console.log(err));
  };

That works perfectly fine and also saves the data in the database, but my login has some issues (?)

const submitHandler = async (data: object) => {
    await fetch("http://localhost:4000/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.status_code === "SUCCESS") {
          localStorage.setItem("userData", JSON.stringify(data.data));
          router.push("/dashboard");
        } else {
          setError("Invalid Credentials!");
        }
      })
      .catch((err) => console.log(err));
  };

When I enter the correct data from the signup, nothing really happens (it should set the jwt token into the localstorage and then redirect me to the dashboard route), any ideas?

CodePudding user response:

This is not redirecting you to login route because if you clearly look at bottom of your signup request handler where you are comparing data.status_code === " SUCCESS" that should be data.status_code === "SUCCESS".

"SUCCESS" & " SUCCESS" both are different.

CodePudding user response:

For me it seems like that you have a typo when you check the data.status_code. You misspelled " SUCCESS" with "SUCCESS". If that was the case, then you can move on, but here is an alternate solution you could use. I also provided a back-end file (I used Node.js with Express).

import React, { useState } from 'react';
import PropTypes from 'prop-types';

async function submitHandler(credentials) {
 return fetch('http://localhost:4000/login', {
   method: 'POST',
   headers: {
     'Content-Type': 'application/json'
   },
   body: JSON.stringify(credentials)
 })
   .then(data => data.json())
}

export default function Login({ setToken }) {
  const [username, setUserName] = useState();
  const [password, setPassword] = useState();

  const handleSubmit = async e => {
    e.preventDefault();
    const token = await submitHandler({
      username,
      password
    });
    setToken(token);
  }

  return(
    <div className="login-wrapper">
      <h1>Please Log In</h1>
      <form onSubmit={handleSubmit}>
        <label>
          <p>Username</p>
          <input type="text" onChange={e => setUserName(e.target.value)} />
        </label>
        <label>
          <p>Password</p>
          <input type="password" onChange={e => setPassword(e.target.value)} />
        </label>
        <div>
          <button type="submit">Submit</button>
        </div>
      </form>
    </div>
  )
}

Login.propTypes = {
  setToken: PropTypes.func.isRequired
};

useToken.js - contains the logic for the custom hook

import { useState } from 'react';

export default function useToken() {
  const getToken = () => {
    const tokenString = localStorage.getItem('token');
    const userToken = JSON.parse(tokenString);
    return userToken?.token
  };

  const [token, setToken] = useState(getToken());

  const saveToken = userToken => {
    localStorage.setItem('token', JSON.stringify(userToken));
    setToken(userToken.token);
  };

  return {
    setToken: saveToken,
    token
  }
}

App.js

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import './App.css';
import Dashboard from '../Dashboard/Dashboard';
import Login from '../Login/Login';
import Preferences from '../Preferences/Preferences';
import useToken from './useToken';

function App() {

  const { token, setToken } = useToken();

  if(!token) {
    return <Login setToken={setToken} />
  }

  return (
    <div className="wrapper">
      <h1>Application</h1>
      <BrowserRouter>
        <Switch>
          <Route path="/dashboard">
            <Dashboard />
          </Route>
          <Route path="/preferences">
            <Preferences />
          </Route>
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

server.js

const express = require('express');
const cors = require('cors')
const app = express();

app.use(cors());

app.use('/login', (req, res) => {
  res.send({
    token: 'test123'
  });
});

app.listen(8080, () => console.log('API is running on http://localhost:4000/login'));
  • Related