how to delete row from database immediately in react js? - node.js

I am able to do axios.delete to remove an item from my database. But won’t be updated immediately unless I refresh the page or go to another page. here is the full component
function GestImages() {
//load Data from db
load data is working fine :
const [images, setImages]=useState([])
useEffect(()=>{
Axios.get("http://localhost:4000/produit/images")
.then(res=>{
setImages(res.data)
})
.catch(err=>{
console.log(err.message)
})
},[])
// delete Data from db
const deleteImage=(id,e)=>{
Axios.delete(`http://localhost:4000/produit/images/${id}`)
.then((res)=>{
setImages(prevImages => prevImages.filter(image => image.id !== id))
})
.catch(err=>{
console.log(err.message)
})
}
return (
<div className="container">
<div className="row row-a">
<div className="col-lg-12 col-md-12 d-flex justify-content-between" style={{backgroundColor:'#000000'}}>
<h1 className="justify-content-start" style={{color:'#FFFFFF'}}>Ajouter des images</h1>
<Link to='/gest-images/add-images' style={{marginTop:"1%"}} ><button className="btn btn-primary justify-content-end">Ajouter</button></Link>
</div>
<div className="col-lg-12 col-md-12 ">
<table className="table table-hover">
<thead>
<tr>
<th scope="col">Produit Name</th>
<th scope="col">Image</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{
images.map(images=>(
<tr key={images.id}>
<th>{images.produits.produitName}</th>
<td style={{width:"30%"}}><img src={"../../images/"+images.pathImage} style={{width:"20%"}} alt="produit img"/></td>
<td><button className="btn btn-danger" onClick={(e)=>deleteImage(images.id)}>Supprimer <FontAwesomeIcon icon={faTrashAlt} style={{color:"#FFFFFF"}}/> </button> </td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
</div>
)
}
export default GestImages

Related

Express.js - Posted data not rendering until refresh the page

I am send and fetch data from MySql Database with Express.js and Sequelize.js. All my code works correctly. My problem is, posted data not rendering on the Handlebars template until refresh the page. I also tried res.render method after SaveSettings method but don't worked. I want to render updated data after redirect.
Solved
You're missing return before settings.update(). Without it, the SaveSettings promise resolves before the update has completed - #Phil
function SaveSettings(Model, values) {
return Model.findByPk(1).then((settings) => {
if (!settings) {
return Model.create(values).catch((e) => console.log(e));
} else {
return settings.update(values).catch((e) => console.log(e));
}
});
}
Routes
router.get("/admin", csrf, isAuth, controller.getGeneral);
router.post("/admin", isAuth, controller.postGeneral);
Controllers
exports.getGeneral = (req, res) => {
Models.General.findByPk(1).then((result) => {
return res.render("dashboard/index", {
title: "General Settings",
data: result,
});
});
};
exports.postGeneral = (req, res) => {
SaveSettings(Models.General, req.body)
.then(() => res.redirect("/admin"));
};
SaveSettings Method
function SaveSettings(Model, values) {
return Model.findByPk(1).then((settings) => {
if (!settings) {
return Model.create(values).catch((e) => console.log(e));
} else {
settings.update(values).catch((e) => console.log(e));
}
});
}
Frontend
<form action="" method="post" class="table-responsive">
<input type="hidden" name="_csrf" value="{{csrfToken}}" />
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-success">Save</button>
</div>
<table class="table table-striped table-sm mt-3">
<thead>
<tr>
<th scope="col">Slot</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td class="align-middle">Name</td>
<td class="align-middle">
<input
name="name"
class="form-control"
type="text"
value="{{data.name}}"
/>
</td>
</tr>
<tr>
<td class="align-middle">Description</td>
<td class="align-middle">
<input
name="description"
class="form-control"
type="text"
value="{{data.description}}"
/>
</td>
</tr>
<tr>
<td class="align-middle">Email</td>
<td class="align-middle">
<input
name="email_address"
class="form-control"
type="email"
value="{{data.email_address}}"
/>
</td>
</tr>
</tbody>
</table>
</form>

Laravel : How download custom blade table as excel

I have this table in blade file in laravel app:
<form method="POST" action="{{url('/download')}}" id="download_form">
#csrf <!-- {{ csrf_field() }} -->
<table class="table font-weight-bold w-100" id="excel_table">
<thead class="table-primary">
<tr>
<th class="text-center">#</th>
<th class="text-center">ناڤ</th>
<th class="text-center">كوم</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">{{$counter}}</td>
<td class="text-right table-primary">{{$student->name}}</td>
<td class="text-center table-primary">{{$sub_total}}</td>
</tr>
</tbody>
</table>
<div>
<input type="hidden" name="file_contente" id="file_contente">
<input type="hidden" value="{{$stage}}" name="stage" id="">
<input type="hidden" value="{{$group}}" name="group" id="">
<button type="submit" id="download" class="btn btn-success">Download to excel</button>
</div>
</form>
</div>
<script>
$(document).ready(function() {
$('#download').click(function() {
var table_content = '<table>';
table_content += $('#excel_table').html();
table_content+= '</table>';
$('#file_content').val(table_content);
$('#download_form').html();
})
})
</script>
the controller is :
public function download(Request $req)
{
$temporary_html_file = './tmp_html/' . time() . '.html';
file_put_contents($temporary_html_file, $req->file_contente);
$reader = IOFactory::createReader('Html');
$spreadsheet = $reader->load($temporary_html_file);
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$filename = $req->stage." ".$req->group . '.xlsx';
$writer->save($filename);
header('Content-Type: application/x-www-form-urlencoded');
header('Content-Transfer-Encoding: Binary');
header("Content-disposition: attachment; filename=\"".$filename."\"");
readfile($filename);
unlink($temporary_html_file);
unlink($filename);
}
I get error :
file_put_contents(./tmp_html/1634558222.html): failed to open stream:
No such file or directory
How can I solve it ? what is the mistake i did?
Edit
after I created the temp_html folder in public folder I get this error :
./tmp_html/1634560521.html is an Invalid HTML file.

Laravel 8 Livewire refresh data after click|model events

I'm trying to create a simple table list view with laravel and livewire component. I can show the component but when I fire an event (change, wiremodel, click) the dataset is not updating, for example, I have an input text to filter my table, when I write on input the request is firing and component is getting it but component nor re-render with the new information
That's my full view
<header class="header py-6">
<div class="flex justify-between">
<h2 class="font-bold text-2xl text-blue-dark leading-tight">
{{ __('messages.Seizures') }}
</h2>
<div class="flex items-end">
<div class="cursor-pointer">
<i class="fas fa-plus-circle text-blue-light text-3xl"></i>
</div>
<div class="pl-8 flex items-center">
<i class="fas fa-filter text-blue-light text-lg"></i>
<input type="text" name="search" id="search-seizure" class="border border-blue-light rounded-full h-8 ml-1 px-4 text-blue-light" wire:model="filter">
</div>
<div class="pl-8 cursor-pointer" wire:click.prevent="toggleTrash()">
#if( $trash )
<i class="fas fa-trash text-blue-light text-xl"></i><i class="fas fa-toggle-on text-blue-light text-xl"></i>
#else
<i class="fas fa-trash text-gray-400 text-xl"></i><i class="fas fa-toggle-off text-xl text-gray-400"></i>
#endif
</div>
</div>
</div>
</header>
<div class="seizure-page">
<table class="table">
<thead>
<tr>
<th>#sortablelink('date', __('messages.Date'), [], ['class' => 'pr-2'])</th>
<th>{{ __('messages.Duration') }}</th>
<th>#sortablelink('location', __('messages.Location'), [], ['class' => 'pr-2'])</th>
<th>{{ __('messages.Notes') }}</th>
<th width="100px" class="text-right">{{ __('messages.Actions') }}</th>
</tr>
</thead>
<tbody>
#foreach($seizures as $seizure)
<tr class="cursor-pointer">
<td>{{ $seizure->date }}</td>
<td class="w-64">{{ $seizure->duration }}</td>
<td>{{ $seizure->location }}</td>
<td class="truncate-cell">{{ $seizure->note }} </td>
<td class="end">
<div class="flex justify-end">
<button wire:click="" class="btn btn-danger btn-sm px-1"><i class="fas fa-info"></i></button>
<button wire:click="edit({{ $seizure }})" class="btn btn-primary btn-sm px-1"><i class="fas fa-pen"></i></button>
<button wire:click="delete({{ $seizure }})" class="btn btn-danger btn-sm px-1"><i class="fas fa-trash text-warm-red"></i></button>
</div>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="flex justify-center pt-4">
{{ $seizures->links('vendor.pagination.neurons-unchained') }}
</div>
</div>
And this is the component logic
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Seizure;
use Carbon\Carbon;
use Livewire\WithPagination;
class Seizures extends Component
{
use WithPagination;
public $trash = false;
public $filter;
public function render()
{
//TODO: Get paginate number from user settings
$seizures = Seizure::sortable(['date' => 'desc'])
->whereNull('deleted_at')
->where('note', 'like', '%' . $this->filter . '%')
->paginate(10);
if( $this->trash) {
$seizures = Seizure::sortable(['date' => 'desc'])
->whereNotNull('deleted_at')
->where('note', 'like', '%' . $this->filter . '%')
->paginate(10);
}
return view('livewire.seizure.index')
->with('seizures', $seizures->appends(\Request::except('page')))
->layout('layouts.dashboard');
}
public function delete(Seizure $seizure) {
$seizure->deleted_at = Carbon::now();
$seizure->save();
$this->gotoPage(1);
}
public function toggleTrash () {
$this->trash = !$this->trash;
}
}
The toggle button for show elements in trash has same problem
Many thanks

The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST. when deleting first item

I'm a beginner in Laravel 7. I am trying to create a checkout form when purchasing items. The problem is whenever I try to delete the first item the 'The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.' shows up. However, I am able to delete the following items under it that I put into the checkout form.
This is my CheckoutController
public function destroy($id)
{
Temp_order::where('id',$id)->delete();
return redirect('checkout')->with('success','Product deleted successfully');
}
And this is the code for the table
<tbody>
#forelse ($order as $item)
<tr>
<td id="item_code">{{ $item->item_code }}</td>
<td class="cart_product_img" id="image">
<img src="" alt="Unavailable" style="width: 70px; height:70px"></img>
</td>
<td id="item_name">
{{ $item->item_name }}
</td>
<td id="price">
₱ {{ number_format($item->price, 2) }}
</td>
<td class="qty" id="qty">
<div class="qty-btn d-flex">
<div class="quantity">
<input type="number" class="qty-text" id="qty" step="1" min="1" max="300" name="quantity" value="{{ $item->quantity }}">
</div>
</div>
</td>
<td id="subtotal">
₱ {{ number_format($item->subtotal, 2) }}
</td>
<td>
<form action="{{ route('checkout.destroy', $item->id) }}" method="post">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm">Remove</button>
</form>
</td>
</tr>
#empty
<tr>
<td>
<p> NO ITEMS IN CART </p>
</td>
</tr>
#endforelse
</tbody>
And this is my route
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('ordering', 'OrderingController')->middleware('auth');
Route::resource('inventory', 'InventoryController')->middleware('auth');
Route::resource('checkout', 'CheckoutController')->middleware('auth');
Can you help me masters?
Try to update CheckoutController
public function destroy(Temp_order $item)
{
$item->delete();
return redirect('checkout')->with('success','Product deleted successfully');
}

Loop Inside node.js module

Here is my module.
module.exports = function (requestUser) {
let content = `
<div id="cpl">
<table id="currentpatientslists">
</table>
</div>
<div id="rp">
<h1>Requested Patients</h1>
</div>
<hr>
<div id="note" >Currently no patients</div>
<div id="rpl">
<table id="requestedpatientslists">
<tr>
<td width="30%"></td>
<td width="30%" class="right"><button>Accept</button></td>
<td width="30%" class="left"><button>Reject</button></td>
</tr>
</table>
</div>`;
return render(content);
}
In the requestedpatientslists table , I want to loop the data in the table row coming from requestUser which is an array. I want to loop it until requestUser.length. How can I do that?
You just need to loop over the users and create the rows for them first
module.exports = function(requestUser) {
// I'm guessing that the user has normal properties like name, etc?
const tableRows = requestUser.map(
user => `
<tr>
<td width="30%">${user.name}</td>
<td width="30%" class="right"><button>Accept</button></td>
<td width="30%" class="left"><button>Reject</button></td>
</tr>
`,
);
const content = `
<div id="cpl">
<table id="currentpatientslists">
</table>
</div>
<div id="rp">
<h1>Requested Patients</h1>
</div>
<hr>
<div id="note" >Currently no patients</div>
<div id="rpl">
<table id="requestedpatientslists">
${tableRows.join('\n')}
</table>
</div>`;
return render(content);
};

Resources