user list table showing twice - javascript

I have list components:
import React,{useState,useEffect} from 'react'
import { Link } from 'react-router-dom'
import UserService from '../services/UserService'
const UserList = () => {
const [users,setUsers] = useState([])
useEffect(() => {
UserService.findAll().then((response)=>{
setUsers(response.data)
}).catch(error=>{
console.log(error)
})
},[users])
const [selectedUserId, setSelectedUserId] = useState();
const handleRowClick = (id) => {
setSelectedUserId(id);
}
return (
<div className='container'>
<h2 className='text-center'>Users</h2>
<div>
<table className='table table-bordered table-stripped'>
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Password</th>
</thead>
<tbody>
{
users.map(
user =>
<tr key={user.id} onClick={() => handleRowClick(user.id)} style={{backgroundColor: selectedUserId === user.id ? "lightblue" : ""}}>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.email}</td>
<td>{user.password}</td>
</tr>
)
}
</tbody>
</table>
</div>
<Link className="btn btn-primary mx-2" to={"/users/save"} state='Create' >New</Link>
<Link className="btn btn-primary mx-2" to={'/update/'+selectedUserId} state='Update'> Edit</Link>
<Link className="btn btn-primary mx-2" to={"/update/"+selectedUserId} state='Delete' >Delete</Link>
</div>
)
}
export default UserList;
//<Link className="btn btn-primary mx-2" to={"/users/save"} onClick={() => setData('Create')} >New</Link>
It shows UserList twice:
I thought because of the React Strict Mode but it wasn't.
Why is my table showing twice? How can I fix this?

Related

Filter function by name React

I need a function to filter by name, The data comes from my Laravel API, I wanted to make a filter on the screen to search for the account name. I am new to React.
import Table from "react-bootstrap/Table";
import axios from "axios";
import { Link } from "react-router-dom";
import { useState, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
const endpoint = "http://localhost:8000/api";
const AccountShow = () => {
const [accounts, setAccounts] = useState([]);
useEffect(() => {
getAllAccounts();
}, []);
const getAllAccounts = async () => {
const response = await axios.get(`${endpoint}/accounts`);
setAccounts(response.data);
};
const deleteAccount = async (id) => {
await axios.delete(`${endpoint}/account/${id}`);
getAllAccounts();
};
return (
<div className="d-grid gap-2">
<div className="row">
<div className="col-8">
<Form className="d-flex m-1">
<Form.Control
type="search"
placeholder="Filtro"
className="me-2"
aria-label="Search"
/>
<Button variant="outline-secondary">Search</Button>
</Form>
</div>
<div className="col-4">
<Link
to="/account/create"
className="col-11 btn btn-outline-primary m-1 "
>
Create
</Link>
</div>
</div>
<Table hover className="">
<thead>
<tr>
<th scope="col">#</th>
<th className="col-2" scope="col">
Nome
</th>
<th className="col-2" scope="col">
Razão Social
</th>
<th scope="col">Status da Conta</th>
<th scope="col">Setor</th>
<th scope="col">Segmento Atuacao</th>
<th scope="col">Natureza Juridica</th>
<th scope="col">Capital</th>
<th scope="col">Funcionarios</th>
<th className="text-center" scope="col">
Ações
</th>
</tr>
</thead>
<tbody>
{accounts.map((account) => (
<tr key={account.id}>
<th>{account.id}</th>
<td>{account.nome}</td>
<td>{account.razaoSocial}</td>
<td>{account.statusConta}</td>
<td>{account.setor}</td>
<td>{account.segmentoAtuacao}</td>
<td>{account.naturezaJuridica}</td>
<td>{account.capital}</td>
<td>{account.funcionarios}</td>
<td className="text-center">
<Link
to={`edit/${account.id}`}
className="btn btn-outline-warning"
>
Editar
</Link>
<button
onClick={() => deleteAccount(account.id)}
className="btn btn-outline-danger m-1"
>
Deletar
</button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
);
};
export default AccountShow;
This is a correct way to filter.
import Table from "react-bootstrap/Table";
import axios from "axios";
import { Link } from "react-router-dom";
import { useState, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
const endpoint = "http://localhost:8000/api";
const AccountShow = () => {
const searchQuery = useState("");
const [accounts, setAccounts] = useState([]);
const [accountToShow, setAccountsToShow] = useState([]);
useEffect(() => {
setAccountsToShow(accounts.filter((account) => /*filter by a specific parameter here depending on what you want to filter it by; by the account.nome field?*/ account.nome.includes(searchQuery)));
}, [accounts, searchQuery]);
useEffect(() => {
getAllAccounts();
}, []);
const getAllAccounts = async () => {
const response = await axios.get(`${endpoint}/accounts`);
setAccounts(response.data);
};
const deleteAccount = async (id) => {
await axios.delete(`${endpoint}/account/${id}`);
getAllAccounts();
};
return (
<div className="d-grid gap-2">
<div className="row">
<div className="col-8">
<Form className="d-flex m-1">
<Form.Control
onChange={({target}) => setSearchQuery(target.value)}
value={searchQuery}
type="search"
placeholder="Filtro"
className="me-2"
aria-label="Search"
/>
<Button variant="outline-secondary">Search</Button>
</Form>
</div>
<div className="col-4">
<Link
to="/account/create"
className="col-11 btn btn-outline-primary m-1 "
>
Create
</Link>
</div>
</div>
<Table hover className="">
<thead>
<tr>
<th scope="col">#</th>
<th className="col-2" scope="col">
Nome
</th>
<th className="col-2" scope="col">
Razão Social
</th>
<th scope="col">Status da Conta</th>
<th scope="col">Setor</th>
<th scope="col">Segmento Atuacao</th>
<th scope="col">Natureza Juridica</th>
<th scope="col">Capital</th>
<th scope="col">Funcionarios</th>
<th className="text-center" scope="col">
Ações
</th>
</tr>
</thead>
<tbody>
{accountsToShow.map((account) => (
<tr key={account.id}>
<th>{account.id}</th>
<td>{account.nome}</td>
<td>{account.razaoSocial}</td>
<td>{account.statusConta}</td>
<td>{account.setor}</td>
<td>{account.segmentoAtuacao}</td>
<td>{account.naturezaJuridica}</td>
<td>{account.capital}</td>
<td>{account.funcionarios}</td>
<td className="text-center">
<Link
to={`edit/${account.id}`}
className="btn btn-outline-warning"
>
Editar
</Link>
<button
onClick={() => deleteAccount(account.id)}
className="btn btn-outline-danger m-1"
>
Deletar
</button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
);
};
export default AccountShow;
You can filter data using
useMemo()
const [accounts, setAccounts] = useState([]);
const [query, setQuery] = useState('');
const filterData = useMemo(() => {
if (accounts && accounts?.length > 0) {
return accounts.filter(item =>
item?.name
.toLocaleLowerCase('en')
.includes(query.trim().toLocaleLowerCase('en')),
);
}
}, [accounts, query]);
you can set query using textbox change event

How can I reduce the quantity with delivery button with react js?

As you can see in the react code, I am trying to reduce the quantity, but I struggle to do it in react. what I want is if click button then quantity should be reduced 1 by 1.
I don't understand what should I do here.
const ManageInventory = () => {
const [products, setProducts] = useProducts();
const handleDelevery = id => {
const handleDelivery = event => { event.preventDefault();
const deliveryInventoryItem = inventoryItem.quantity(quantity-1);
}
const handleDelete = id => {
const proceed = window.confirm('Are Your Sure?');
if(proceed){
const url =`http://localhost:5000/product/${id}`;
fetch(url, {
method: 'DELETE'
})
.then(res => res.json())
.then(data => {
console.log(data);
const remaining = products.filter(product => product._id !==id);
setProducts(remaining);
})
}
}
return (
<div className=''>
<h2 className='product-title'>All Products {products.length} </h2>
<div>
</div>
<div>
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>Image</th>
<th>Prodct Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Supplier</th>
<th colSpan={2}>Edit</th>
</tr>
</thead>
<tbody>
{
products.map(product => <tr
key={product._id}
product={product}>
<td><img src={product.img} alt="" /> </td>
<td>{product.name}</td>
<td> {product.price}</td>
<td>{product.quantity}</td>
<td>{product.supplier}</td>
<td><button className='manage-btn' onClick={()=> handleDelete(product._id)}>Delete</button></td>
<td><button className='manage-btn' onClick={()=> handleDelevery()}>Delivered</button></td>
</tr>
)
}
</tbody>
</Table>
</div>
<button className='add-product-link'><Link to='/addproduct'>Add Product</Link></button>
</div>
);
};

Add search dropdown for React table in JHipster

I have this React table in JHipster project:
<div className="table-responsive">
{activePairsList && activePairsList.length > 0 ? (
<Table responsive>
<thead>
<tr>
<th className="hand" onClick={sort('id')}>
ID <FontAwesomeIcon icon="sort" />
</th>
<th className="hand" onClick={sort('exchangeId')}>
Exchange Id <FontAwesomeIcon icon="sort" />
</th>
...........
<th />
</tr>
</thead>
<tbody>
{activePairsList.map((activePairs, i) => (
<tr key={`entity-${i}`} data-cy="entityTable">
<td>
<Button tag={Link} to={`${match.url}/${activePairs.id}`} color="link" size="sm">
{activePairs.id}
</Button>
</td>
<td>{activePairs.exchangeId}</td>
</tr>
))}
</tbody>
</Table>
) : (
!loading && <div className="alert alert-warning">No Active Pairs found</div>
)}
</div>
I would like to add search functionality for this table. I want to add Filter by exchange to be present and when any exchange is selected the table should be filtered to show only data for the selected exchange. Do you know how this can be implemented?
I've worked on your issue in stackblitz. I create a link to a simple sample of what you want you can check it here.
I've added an input to filter data is passing to the table on input changes. Hope you find it useful.
I prepared a ReactJS/Typescript solution and implemented it on the JHipster 7.
NOTE: if you have no active-pairs entity, apply the below steps.Else continue from step 4.
First of all, create a monolith web project with JHipster 7 & ReactJS.
Create an entity of ActivePairs with JDL Studio and download
the JDL file from the JDL Studio. (activepairs-jdl.jdl)
If you want to pagination add this expression in your jdl file : paginate all with pagination
Copy the activepairs-jdl.jdl file to the root folder of your
project.
Open a terminal on the root folder of your project and write below command:
jhipster jdl activepairs-jdl.jdl
Go this path in your project :
src>main>webapp>app>entities>active-pairs>active-pairs.tsx
Copy the below code and paste it in your active-pairs.tsx file.
import { connect } from 'react-redux';
import { Link, RouteComponentProps } from 'react-router-dom';
import { Button, Col, Row, Table } from 'reactstrap';
import { ICrudGetAllAction, ICrudSearchAction } from 'react-jhipster';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { IRootState } from 'app/shared/reducers';
import { getEntities } from './active-pairs.reducer';
import { IActivePairs } from 'app/shared/model/active-pairs.model';
import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants';
export interface IActivePairsProps extends StateProps, DispatchProps, RouteComponentProps<{ url: string }> { }
export const ActivePairs = (props: IActivePairsProps) => {
useEffect(() => {
props.getEntities();
}, []);
const { activePairsList, match, loading = true } = props;
const myDataSource = props.activePairsList;
const [myActivePairsList, setActivePairsList] = useState(props.activePairsList);
const [dropdownList, setDropdownList] = useState([])
const [focus, setFocus] = useState(false)
const [searchValue, setSearchValue] = useState('')
const [arrOfSelectedExId, setArrOfSelectedExId] = useState([])
useEffect(() => {
const unrepeated = activePairsList.reduce((acc, curr) => {
if (acc.find(item => item.exchangeId === curr.exchangeId)) {
return acc
}
return acc.concat(curr)
}, [])
const regexes = [`${searchValue}`];
const filtered = unrepeated.filter(item => regexes.some(regex => item.exchangeId.match(regex)));
setDropdownList(filtered);
setActivePairsList(activePairsList);
}, [searchValue, activePairsList])
useEffect(() => {
if (arrOfSelectedExId.length) {
setActivePairsList(myDataSource.filter(activePairs => {
return arrOfSelectedExId.includes(activePairs.exchangeId)
}))
} else {
setActivePairsList(myDataSource)
}
}, [arrOfSelectedExId])
return (
<div>
<input value={searchValue} onFocus={() => setFocus(true)} onBlur={(e) => setFocus(false)} onChange={e => setSearchValue(e.target.value)} />
{(dropdownList.length !== 0) && focus && (<div className="dropdown-parent">
{
dropdownList.map((item, i) => {
return <div key={'drp' + i} className={arrOfSelectedExId.includes(item.exchangeId) ? 'selected' : ''} onMouseDown={(e) => {
e.preventDefault()
setArrOfSelectedExId(prev => {
if (prev.includes(item.exchangeId)) {
return prev.filter(x => x !== item.exchangeId)
} else {
return prev.concat(item.exchangeId)
}
})
// setSearchValue(item.exchangeId)
}}>{item.exchangeId}</div>
})
}
</div>)}
<h2 id="active-pairs-heading">
Active Pairs
<Link to={`${match.url}/new`} className="btn btn-primary float-right jh-create-entity" id="jh-create-entity">
<FontAwesomeIcon icon="plus" />
Create new Active Pairs
</Link>
</h2>
<div className="table-responsive">
{myActivePairsList && myActivePairsList.length > 0 ? (
<Table responsive>
<thead>
<tr>
<th>ID</th>
<th>Exchange Id</th>
<th />
</tr>
</thead>
<tbody>
{myActivePairsList.map((activePairs, i) => (
<tr key={`entity-${i}`}>
<td>
<Button tag={Link} to={`${match.url}/${activePairs.id}`} color="link" size="sm">
{activePairs.id}
</Button>
</td>
<td>{activePairs.exchangeId}</td>
<td className="text-right">
<div className="btn-group flex-btn-group-container">
<Button tag={Link} to={`${match.url}/${activePairs.id}`} color="info" size="sm">
<FontAwesomeIcon icon="eye" /> <span className="d-none d-md-inline">View</span>
</Button>
<Button tag={Link} to={`${match.url}/${activePairs.id}/edit`} color="primary" size="sm">
<FontAwesomeIcon icon="pencil-alt" /> <span className="d-none d-md-inline">Edit</span>
</Button>
<Button tag={Link} to={`${match.url}/${activePairs.id}/delete`} color="danger" size="sm">
<FontAwesomeIcon icon="trash" /> <span className="d-none d-md-inline">Delete</span>
</Button>
</div>
</td>
</tr>
))}
</tbody>
</Table>
) : (
!loading && <div className="alert alert-warning">No Active Pairs found</div>
)}
</div>
</div>
);
};
const mapStateToProps = ({ activePairs }: IRootState) => ({
activePairsList: activePairs.entities,
loading: activePairs.loading,
});
const mapDispatchToProps = {
getEntities,
};
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;
export default connect(mapStateToProps, mapDispatchToProps)(ActivePairs);
copy below css codes in your app.scss file :
h1,
p {
font-family: sans-serif;
}
.selected {
background-color: rgb(190, 188, 188);
}
.dropdown-parent {
max-height: 80px;
width: 200px;
overflow-y: scroll;
border: 1px solid black;
background-color: white;
position: absolute;
}
Run this command ./mvnw
You should see a search box at the top of your table.
As you see I selected 98 and It listed just the rows which have the
values of ExchangeID is 98
Thanks.

if ternario does not work, function has value but never used says

I am new with programing and I want to use if ternario, but it doesn't work. I have two functions and I create a third function to show one of them or the other. It is an application in ReactJS. Below is the code:
import { Table } from "react-bootstrap";
import { Link } from "react-router-dom";
import { useCartContext } from "../../Context/CartContext";
const emptyCart = () => {
return(
<>
<div>
<h3>The Cart is empty</h3>
<p>
Return to home to see our products
</p>
<Link to='/' ><button className="btn btn-info"> Home </button></Link>
</div>
</>
);
};
const CartFunction = () => {
const { list, totalPrice } = useCartContext();
return (
<Table striped hover>
<thead>
<tr>
<th>Product</th>
<th>Title</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{list.map((varietal) => (
<tr key={varietal.id}>
<td>
<img
src={varietal.pictureUrl}
alt='img'
style={{ width: "82px" }}
/>
</td>
<td>{varietal.title}</td>
<td>{varietal.count}</td>
<td>${varietal.price}</td>
</tr>
))}
</tbody>
<thead>
<tr>
<td colSpan="3">Total</td>
<td>${totalPrice()}</td>
</tr>
</thead>
</Table>
);
};
const CartComponent = () => {
const { list } = useCartContext();
return (
<>
{list.length !== 0 ? <CartFunction /> : <emptyCart />}
</>
);
};
export default CartComponent;
Visual Code it says that emptyCard has a value but it is never used. If there is someone that could help me I would appreciate it. Cheers

How can I get the value from select option from Meteor/React?

I have implemented the webapp by Meteor/React with some functions.
Then I have one function which I need the value from select option.
I see some example to use setState. But the code I used is different.
I try to use some functions/ways but I cannot get the update value.
In this code I use day1Changed function to process select value to update.
Please help me to get the value from select from the following code:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Table, Alert, Button, FormGroup, FormControl } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Registers } from '../../api/registers';
const handleRemove = (registerId) => {
if (confirm('Are you sure? This is permanent!')) {
Meteor.call('registers.remove', registerId, (error) => {
if (error) {
console.log(error.reason, 'danger');
} else {
console.log('success');
}
});
}
};
const toggleChecked = (registerId, paid) => {
Meteor.call('registers.setChecked', registerId, !paid);
}
const day1Changed = (registerId) => {
console.log(this.day1.value);
Meteor.call('registers.day1Changed', registerId, this.day1.value);
}
const DSRegisters = ({ registers, totalCount, match, history }) => (
<div className="Registers">
<div className="page-header clearfix">
<br />
<br />
<h4 className="pull-left">Registration </h4> <h4>All user {totalCount} </h4>
<br />
<br />
<Link className="btn btn-success" to={`${match.url}/upload`}>Upload User</Link>
<Link className="btn btn-success pull-right" to={`${match.url}/new`}>Add</Link>
</div>
{registers.length ? <Table striped responsive>
<thead>
<tr>
<th>Item</th>
<th>Salution</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Age</th>
<th>Province</th>
<th>Bhumdharm</th>
<th>Amount</th>
<th>Paid</th>
<th>15/9/60</th>
<th>16/9/60</th>
<th>17/9/60</th>
<th>Accommodation</th>
<th>Remark</th>
<th>Updated</th>
<th>Created</th>
<th>User</th>
<th />
<th />
</tr>
</thead>
<tbody>
{registers.map(({ _id, gender, salution, firstname, lastname, province, bhumdharmlevel, age, amount, paid, day1, day2, day3, accommodation, remark, username, createdAt, updatedAt }, index) => (
<tr key={_id}>
<td>{index+1}</td>
<td>{salution}</td>
<td>{firstname}</td>
<td>{lastname}</td>
<td>{gender}</td>
<td>{age}</td>
<td>{province}</td>
<td>{bhumdharmlevel}</td>
<td>{amount}</td>
<td>
<input
type="checkbox"
readOnly
checked={paid}
onClick={() => toggleChecked(_id,paid)}
/>
</td>
<td>
<FormGroup>
<FormControl
componentClass="select"
name="day1"
inputRef={day1 => (this.day1 = day1)}
defaultValue={day1}
onChange={() => day1Changed(_id, day1)}>
<option value=""></option>
<option value="leave">Leave</option>
<option value="come">Come</option>
<option value="absense">Absense</option>
</FormControl>
</FormGroup>
</td>
<td>{day2}</td>
<td>{day3}</td>
<td>{accommodation}</td>
<td>{remark}</td>
<td>{updatedAt.getDate()}/{updatedAt.getMonth()+1}/{updatedAt.getFullYear()+543} {updatedAt.getHours()}:{(updatedAt.getMinutes()<10?'0':'')+updatedAt.getMinutes()}</td>
<td>{createdAt.getDate()}/{createdAt.getMonth()+1}/{createdAt.getFullYear()+543}</td>
<td>{username}</td>
<td>
<Button
bsStyle="primary"
onClick={() => history.push(`${match.url}/${_id}/edit`)}
block
>Edit</Button>
</td>
<td>
<Button
bsStyle="danger"
onClick={() => handleRemove(_id)}
block
>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table> : <Alert bsStyle="warning">Nobody yet!</Alert>}
</div>
);
DSRegisters.propTypes = {
regs: PropTypes.object,
registers: PropTypes.arrayOf(PropTypes.object).isRequired,
totalCount: PropTypes.number.isRequired,
match: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
};
export default createContainer(() => {
const subscription = Meteor.subscribe('registers');
return {
registers: Registers.find({}, { sort: { createdAt: 1 } }).fetch(),
totalCount: Registers.find({}).count(),
};
}, DSRegisters);
You can get the value from a select option like snippet bellow:
handleChange(name, e) {
this.setState([name]: e.target.value)
}
<select className="ui dropdown" onClick={this.handleChange.bind(this, 'STATE_NAME_HERE')}>
<option value="1">Male</option>
</select>
This code works with Meteor-React-SemanticUi

Categories

Resources