AsrulDev

AsrulDev

Hari 20: React Fetch Api

30 Hari Javascript

Hari 20: React Fetch Api

Subscribe to my newsletter and never miss my upcoming articles

Input pada React

Pada react kita dapat mengambil nilai input menggunakan e.target.value, brikut contoh penulisan input pada react.

const [nama, updateNama] = setState('')
<input type="text" placeholder="name" onChange={(e) => updateNama(e.target.value)} />

Pada kasus ini kita akan menggunakan contoh pada halaman register. Buat file page/Register.js, yang isinya seperti berikut.

File page/Register.js

import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { createUser } from "../actions/user.action";

const Register = (props) => {
  const dispatch = useDispatch();
  const [user, updateUser] = useState({});

  const submitForm = (e) => {
    e.preventDefault();
    dispatch(createUser(user)).then((res) => {
      if (res.data.status === 200) {
        window.location.href = "/";
      }
    });
  };

  return (
    <div className="page">
      <h1 className="page-title">Register 30 Hari Js</h1>

      <form className="register" onSubmit={(e) => submitForm(e)}>
        <label>Nama</label>
        <input
          type="text"
          autoComplete={"false"}
          placeholder="Nama elu"
          onChange={(e) => {
            updateUser({ ...user, name: e.target.value });
          }}
        />

        <label>Label</label>
        <input
          type="text"
          autoComplete={"false"}
          placeholder="Label"
          onChange={(e) => {
            updateUser({ ...user, label: e.target.value });
          }}
        />

        <label>Link Profile</label>
        <input
          type="text"
          autoComplete={"false"}
          placeholder="ex. <http://fb.com/image.png>"
          onChange={(e) => {
            updateUser({ ...user, picture: e.target.value });
          }}
        />

        <label>Email</label>
        <input
          type="email"
          autoComplete={"false"}
          placeholder="email"
          onChange={(e) => {
            updateUser({ ...user, email: e.target.value });
          }}
        />

        <label>No Hp</label>
        <input
          type="text"
          autoComplete={"false"}
          placeholder="Phone"
          onChange={(e) => {
            updateUser({ ...user, phone: e.target.value });
          }}
        />

        <label>Website</label>
        <input
          type="text"
          autoComplete={"false"}
          placeholder="Link web"
          onChange={(e) => {
            updateUser({ ...user, website: e.target.value });
          }}
        />

        <label>Summary</label>
        <textarea
          rows="5"
          autoComplete={"false"}
          placeholder="summary..."
          onChange={(e) => {
            updateUser({ ...user, summary: e.target.value });
          }}
        ></textarea>

        <label>Password</label>
        <input
          type="password"
          autoComplete={"false"}
          placeholder="rahasia"
          onChange={(e) => {
            updateUser({ ...user, password: e.target.value });
          }}
        />

        <button type="submit" onClick={(e) => submitForm(e)}>
          Register
        </button>
      </form>
    </div>
  );
};

export default Register;

Kemudian ubah file RouterApp.js sehingga seperti berikut.

import React, { Component, Fragment } from "react";
import { BrowserRouter, Switch, Route, Link } from "react-router-dom";

import Home from "./pages/Home";
import About from "./pages/About";
import Register from "./pages/Register";

class RouterApp extends Component {
  render() {
    return (
      <BrowserRouter>
        <Fragment>
          <nav>
            <li>
              {" "}
              <Link to="/"> Home </Link>{" "}
            </li>
            <li>
              {" "}
              <Link to="/about"> About </Link>{" "}
            </li>
            <li>
              {" "}
              <Link to="/register"> Register </Link>{" "}
            </li>
          </nav>

          <main>
            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/about" exact component={About} />
              <Route path="/register" exact component={Register} />
            </Switch>
          </main>
        </Fragment>
      </BrowserRouter>
    );
  }
}

export default RouterApp;

Action simpan ke database

Ubah pada file user.action.js untuk menambah kode sebagai proses untuk entry data ke dalam server penyedia API, sehingga kode menjadi seperti berikut.

import axios from "axios";

const baseUrl = `https://warm-refuge-26108.herokuapp.com`;

export const getUsers = () => {
  return async (dispatch) => {
    dispatch({
      type: "GET_USER_REQUEST",
    });
    try {
      const result = await axios.get(baseUrl + `/users`);
      dispatch({
        type: "GET_USER_DONE",
        payload: result.data,
      });
    } catch (error) {
      dispatch({
        type: "GET_USER_ERROR",
      });
    }
  };
};

export const createUser = (data) => {
  return async (dispatch) => {
    try {
      const result = await axios.post(baseUrl + `/users`, data);
      return result;
    } catch (error) {
      dispatch({
        type: "GET_USER_ERROR",
      });
    }
  };
};

Hasil Kode, akan seperti berikut:

https://raw.githubusercontent.com/AsrulLove/img-db/master/network.png

Hasil, data setelah kembali ke halaman home.

https://raw.githubusercontent.com/AsrulLove/img-db/master/tertambah.png

 
Share this
Proudly part of