Refactoring

Kita akan merapihkan code lebih sederhana

App.js

import React, {Component} from 'react';
import { Route, Redirect, Switch } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';

import Movies from './components/movies';
import MovieForm from './components/movieForm';
import Rentals from './components/Rentals';
import NotFound from './components/notFound';
import Customers from './components/Customers';
import NavBar from './components/NavBar';
import LoginFrom from './components/LoginForm';
import RegisterForm from './components/RegisterForm';
import Logout from './components/Logout';
import auth from './services/AuthService';

import "react-toastify/dist/ReactToastify";
import './App.css';

class App extends Component {
  state = {};

  componentDidMount() {
    const user = auth.getCurrentUser();
    this.setState({ user });
  } 
  
  render() {
    return (
      <>
      <ToastContainer />
        <NavBar user={this.state.user} />
        <main className="container">
          <Switch>
            <Route path="/register" component={RegisterForm} />
            <Route path="/login" component={LoginFrom} />
            <Route path="/logout" component={Logout} />
            <Route path="/movies/:id" component={MovieForm} />
            <Route path="/movies" component={Movies}></Route>
            <Route path="/customers" component={Customers}></Route>
            <Route path="/rentals" component={Rentals}></Route>
            <Route path="/not-found" component={NotFound}></Route>
            <Redirect from="/" exact to="/movies" />
            <Redirect to="not-found" />
          </Switch>
        </main>
      </>
    );
  }
}

export default App;

LoginFrom.jsx

import React, { Component } from "react";
import Joi from "joi-browser";
import Form from "./Common/Form";
import auth from '../services/AuthService';

class LoginForm extends Form {
    state = {
        data : {
            username: '',
            password: ''
        },
        errors: {}
    };

    schema = {
        username: Joi.string().required().label("Username"),
        password: Joi.string().required().label("Password")
    };
    
    doSubmit = async () => {
        try {
            const { data } = this.state;
            await auth.login(data.username, data.password);
            // console.log(jwt)
            window.location = "/";
        } catch (error) {
            if (error.response && error.response.status === 400) {
                const errors = { ...this.state.errors };
                errors.username = error.response.data;
                this.setState({ errors });
            }
        }
    };

    render(){
        return (
            <>
                <div>
                    <h1>Login</h1>
                    <form onSubmit={this.handleSubmit} >
                        {this.renderInput('username', 'Username')}
                        {this.renderInput('password', 'Password', "password")}
                        {this.renderButton('Login')}
                    </form>
                </div>
            </>
        )
    }
}

export default LoginForm

AuthService.js

import jwtDecode from 'jwt-decode';
import http from './HttpService';

const apiEndpoint = 'http://localhost:3900/api/auth';
const tokenKey = "token";

export async function login(email, password) {
    const { data: jwt } = await http.post(apiEndpoint, { email, password });
    localStorage.setItem(tokenKey, jwt);
}

export function loginWithJwt(jwt) {
    localStorage.setItem(tokenKey, jwt);
}

export function logout() {
    localStorage.removeItem(tokenKey);
}

export function getCurrentUser() {
    try {
        const jwt = localStorage.getItem(tokenKey)
        return jwtDecode(jwt);
      } catch (error) {
        return null;
    }
}

export default {
    login,
    loginWithJwt,
    logout,
    getCurrentUser
}

RegisterForm.jsx

import React from "react";
import Joi from "joi-browser";
import Form from "./Common/Form";
import * as UserService from '../services/UserService';
import auth from "../services/AuthService";

class RegisterForm extends Form {
    state = { 
        data: { username: "", password: "", name: "" },
        errors: {}
     };

    schema = {
        username: Joi.string().required().label("Username"),
        password: Joi.string().required().label("Password"),
        name    : Joi.string().required().label("Name")
    };

    doSubmit = async () => {
        try {
            const response = await UserService.register(this.state.data); 
            // console.log(response)
            auth.loginWithJwt(response.headers["x-auth-token"]);
            window.location = "/";
        } catch (error) {
            if (error.response && error.response.status === 400) {
                const errors = { ...this.state.errors };
                errors.username = error.response.data;
                this.setState({ errors });
            }
        }
    }

    render() { 
        return (
            <>
                <div>
                    <h1>Register</h1>
                    <form onSubmit={this.handleSubmit} >
                        {this.renderInput('username', 'Username')}
                        {this.renderInput('password', 'Password', "password")}
                        {this.renderInput('name', 'Name')}
                        {this.renderButton('Register')}
                    </form>
                </div>
            </>
        );
    }
}
 
export default RegisterForm;

Logout.jsx

import React, {Component} from "react";
import auth from '../services/AuthService';

class Logout extends Component {
    componentDidMount() {
        auth.logout();

        window.location = "/";
    }

    render() {
        return null;
    }
}

export default Logout;

Last updated

Was this helpful?