<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
class Quotes extends ResourceController
{
protected $format = 'json';
protected $modelName = 'App\Models\Quotes_model';
public function create()
{
$quote = $this‐>request‐>getPost('quote');
$data = [
'quote' => $quote,
];
$simpan = $this‐>model‐>insertQuotes($data);
if ($simpan) {
$msg = ['message' => 'Created quote successfully'];
$response = [
'status' => 200,
'error' => false,
'data' => $msg,
];
return $this‐>respond($response, 200);
}
}
public function index()
{
return $this‐>respond($this‐>model‐>findAll(), 200);
}
Penjelasan!
Oke setelah rest api sudah dibuat kita tinggal mainkan rest api
tersebut di react jsnya. Langsung buka saja
tersebut di react jsnya. Langsung buka saja
file react/src/components/Home.js . Tambah kodenya jadi seperti
ini:
import React, { Component } from "react";
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
listquotes: [],
quotes: "",
};
this.onChange = this.onChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
onChange(event) {
this.setState({ quotes: event.target.value });
}
handleSubmit(event) {
fetch("http://localhost:8080/quotes/create", {
method: "post",
headers: {
Accept: "application/json",
"Content‐Type": "application/x‐www‐form‐urlencoded",
},
body: `quote=${this.state.quotes}`,
})
.then((respon) => respon.json())
.then((ra) => {
if ((ra.status = +200)) {
this.componentDidMount();
} else {
alert("Data don't saved");
}
});
event.preventDefault();
}
componentDidMount() {
fetch("http://localhost:8080/quotes")
.then((respon) => respon.json())
.then((ra) =>
this.setState({
listquotes: ra,
})
);
}
render() {
return (
<div class="container">
<div class="row">
<div class="col">
<div class="d‐flex justify‐content‐center">
<form onSubmit={this.handleSubmit}>
<label>
<input
type="text"
name="name"
class="form‐controll"
value={this.state.quotes}
onChange={this.onChange}
/>
</label>
<input
class="btn btn‐primary btn‐sm"
type="submit"
value="Add Quotes"
/>
</form>
</div>
<table class="table table‐hover">
<thead>
<tr>
<th scope="col">Quotes</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{this.state.listquotes.map((data) => {
return (
<tr>
<td>{data.quote}</td>
<td class="d‐flex justify‐content‐around">
<a
href="#"
class="badge badge‐danger"
>
delete
</a>
<a
href="#"
class="badge badge‐warning"
>
edit
</a>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
Penjelasan!.
Berikut hasilnya:
Balas
Tinggalkan Balasan
Komentar
Nama *
Email *
Situs Web
Simpan nama, email, dan situs web saya pada peramban ini untuk
komentar saya berikutnya.
Kirim Komentar
Kategori
codeigniter 4 ﴾5﴿
﴾4﴿
PHP ﴾4﴿
Python ﴾7﴿
react js ﴾5﴿
Termux ﴾5﴿
vps ﴾1﴿