Why I can't get the right state when I try to console log inside on my onchange handler? - reactjs

I have problem regarding on getting all the state inside of my HandlerInputChange the data already updated into 10 data however when I console it log inside of my handler it shows the default array value which is 5.
Question: How to get the all the state data inside of my handler?
Goal: To get all the state on my handler
Logs:
My UseState:
const [data, setData] = useState(defaultArray)
My Handler:
useEffect(() => {
console.log("data" , data)
}, [data])
const handleInputChange = (e, i) => {
const { name, value } = e.target;
const list = [...data];
console.log(list);
}
Add Rows Function:
const AddRows = () => {
//loop here the keys listed
let initialKey = 0;
const x = data.slice(-1);
initialKey = parseInt(x[0]['key']);
let newArr=[...Array(5)].map((_,i)=>{
let val=i + 1 +initialKey;
return {
key: ""+val+"",
customer: <select className="form-control" name="customer" onChange={(e,i) => handleInputChange(e,val)}>
<option disabled selected>Select Customer</option>
<option >LEXI INC / joseph</option>
<option >LEXI INC / james</option>
<option >LEXI INC / charlie</option>
<option >LEXI INC / pam</option>
<option >LEXI INC / regorio</option>
</select>,
bank: <select className="form-control" name="bank" onChange={(e,i) => handleInputChange(e,val)}>
<option disabled selected>Select Bank</option>
<option >BDO</option>
<option >MAY BANK</option>
<option >EAST WEST BANK</option>
<option >UNION BANK</option>
<option >BPI</option>
</select>,
branch: <input className="form-control" placeholder="Branch" name="branch" onChange={(e,i) => handleInputChange(e,val)}/>,
checkNo: <input type="number" className="form-control" name="checkNo" placeholder="Check No." onChange={(e,i) => handleInputChange(e,val)}/>,
checkDate: <input type="date" name="checkDate" className="form-control" onChange={(e,i) => handleInputChange(e,val)}/>,
amount: <input
name="amount"
className="form-control"
placeholder="Amount"
onChange={(e,i) => handleInputChange(e,val)}
/>,
remarks: <select className="form-control" name="remarks" onChange={(e,i) => handleInputChange(e,val)}>
<option disabled selected>Select Remarks</option>
<option >Test</option>
</select>
}
});
setData([...data, ...newArr]);
}
Button:
<button type="submit" class="btn btn-danger" onClick={() => AddRows()}>Add Row</button>

Your handleInputChange is not the problem. Normally, it will be return an array with 10 elements like the variable defaultArray.
perhaps the problem is line 1 and 3

Related

Can you loop through an api endpoint? date data for example

I made a little project that renders a football league of your choice and then the standings for that year plus the overall points won. But now let's say I would like to display in one render the 10-year history of the said league to see who has won the most points. How can I manipulate the endpoint of this API :
https://api-football-standings.azharimm.site/leagues/${selectedLeague}/standings?season=2011
so let's say from 2011 till 2021. What is this process called?
Thank you in advance,
The code is below:
import React, {useState,useEffect} from "react";
import axios from "axios";
import {TailSpin} from "react-loader-spinner";
const Standings = () => {
const [data,setData] = useState([]);
const [loading, setLoading] = useState(false);
const [selectedLeague,setSelectedLeague] = useState('eng.1');
useEffect(()=> {
setLoading(true);
axios(
`https://api-football-standings.azharimm.site/leagues/${selectedLeague}/standings?season=2011`
).then(res=> {
console.log(res.data.data.standings);
setData(res.data.data.standings);
} ).catch(err => console.log(err))
.finally(() => setLoading(false));
},[selectedLeague]);
return (
<div className="standings-container">
<div className="select-container">
<select
name="select-league"
id="select-league"
defaultValue={selectedLeague}
onChange={(e) => setSelectedLeague(e.target.value)}
>
<option value="arg.1">Argentine Liga Profesional de Fútbol</option>
<option value="aus.1">Australian A-League</option>
<option value="bra.1">Brazilian Serie A</option>
<option value="chn.1">Chinese Super League</option>
<option value="ned.1">Dutch Eredivisie</option>
<option value="eng.1">English Premier League</option>
<option value="fra.1">French Ligue 1</option>
<option value="ger.1">German Bundesliga</option>
<option value="idn.1">Indonesian Liga 1</option>
<option value="ita.1">Italian Serie A</option>
<option value="jpn.1">Japanese J League</option>
<option value="mys1">Malaysian Super League</option>
<option value="mex.1">Mexican Liga BBVA MX</option>
<option value="por.1">Portuguese Liga</option>
<option value="rus.1">Russian Premier League</option>
<option value="sgp.1">Singaporean Premier League</option>
<option value="esp.1">Spanish Primera División</option>
<option value="tha.1">Thai Premier League</option>
<option value="tur.1">Turkish Super Lig</option>
<option value="uga.1">Ugandan Super League</option>
</select>
</div>
<div className="standing-results">
{ loading ? <TailSpin color="#00BFFF" height={80} width={80} /> :
data.map((data, index) => (
<div key={data.team.id} className="standing-info">
<h1>
<span>{`${index+1}.`} <img src={data.team.logos[0].href} alt="#"/></span>
{data.team.shortDisplayName}
{JSON.stringify(data.stats[6].value)}
</h1>
</div>
))
}
</div>
</div>
);
};
export default Standings;

How can I send a value with Select tag through the useState on ReactJS

I want my code to send the variable from onChange to useState here's my code at for displaying my table on each row
const dataTableElements = entireListData
.slice(0, maxRow)
.map((entireListData, index) => {
var dotStatus = null;
if (entireListData.PriceStatus == true) {
dotStatus = <GreenDot>{entireListData.Price}</GreenDot>;
} else {
dotStatus = <RedDot>{entireListData.Price}</RedDot>;
}
return (
<Tr data-index={index}>
<Td>{entireListData.no}</Td>
<Td>{entireListData.BillNo}</Td>
<Td>{entireListData.Product}</Td>
<Td>
<StatusTableBox>{dotStatus}</StatusTableBox>
</Td>
</Tr>
);
});
next is my select tag
return (
<div>
<Tabbar />
<div>
<p>
Show
<select
value={entireListData.no}
onChange={() => {
sendCurrentRow(entireListData.no);
}}
>
{rowTableElement}
</select>
Entires
</p>
</div>
from the result of the above, it shows in console "undefined".
Usually the select tag gives an event in the onChange method that you can use to extract the value which selected, take a look at this example:
<select
value={entireListData.no}
onChange={(event) => {
sendCurrentRow(event.target.value);
}}
>
//here should be your options with different values
<option value="1">
1
</option>
<option value="2">
2
</option>
// I don't know this value has the option or not => {rowTableElement}
</select>

filter array doesn't work in React component

I wanna sort the sizes of my clothes but when I click to elect the size, no matter what I choose, it stays "All"...Is there anything wrong with my function filterProducts?
function Filter(props) {
return (
<div className="filter">
<div className="filter-result">{props.count} Products</div>
<div className="filter-sort">
Order
<select value={props.sort} onChange={props.sortProducts}>
<option value="latest">Latest</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</div>
<div className="filter-size">
Filter
<select value={props.size} onChange={props.filterProducts}>
<option value="">All</option>
<option value="">XS</option>
<option value="">S</option>
<option value="">M</option>
<option value="">L</option>
<option value="">XL</option>
<option value="">XXL</option>
</select>
</div>
</div>
);
}
My codesand link:https://codesandbox.io/s/redux-shop-cart-forked-tlpek?file=/src/App.js
All the size options were missing unique value props, they were all value="".
Update the value props to match your data:
Filter
<select value={props.size} onChange={props.filterProducts}>
<option value="">All</option>
<option value="XS">XS</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
<option value="XXL">XXL</option>
</select>
You also had a typo in filterProducts in App where you reset the state to a product property instead of products. This wasn't allowing the "All" filter value to work.
filterProducts = (event) => {
if (event.target.value === "") { // all
this.setState({
size: event.target.value,
products: data.products // <-- reset products!!
});
} else {
this.setState({
size: event.target.value,
products: data.products.filter(
(product) => product.availableSizes.indexOf(event.target.value) >= 0
)
});
}
};

How can I pass calculated amount to state in react

How can I pass currentBook, currentUnits and calculated total during on click on the Record button
Now it just displays the entered value under the purchased book section. I would like to display the data and calculated amount during on click on Record button. Could someone please advise
ie Amount = units * price
for example it should display following result 1. Mathematics 6 300
https://codesandbox.io/s/falling-grass-gwpf9?file=/src/App.js
function App() {
const [currentBook, setCurrentBook] = useState('')
const [currentUnits, setCurrentUnits] = useState('')
const [currentPrice, setCurrentPrice] = useState('')
const [currentRecord, setCurrentRecord] = useState({book:'', units:'', price:''});
const changeBook = (newBook) => {
setCurrentBook(newBook);
}
const changeUnits = (newunits) => {
setCurrentUnits(newunits);
}
const changePrice = (newprice) => {
setCurrentPrice(newprice);
}
const calculateTotal = (e) => {
var cal_total = currentUnits * currentPrice;
setCurrentRecord(currentBook, currentUnits, cal_total );
//setCurrentRecord({ ...currentRecord, [e.target.name]: e.target.value });
}
return (
<div className="App">
<div>
<h1>Online Shopping</h1>
</div>
<div className="flexbox-container">
<div className="maintransaction">
<h3>Choose a book</h3>
<div className="container">
<select defaultValue={'DEFAULT'} onChange={(event) => changeBook(event.target.value)}>
<option value="DEFAULT" disabled>Choose a book ...</option>
<option value="maths">Mathematics</option>
<option value="science">Science</option>
<option value="english">English</option>
<option value="German">German</option>
</select>
</div><br></br>
<div className="quantity">
<span className="units">
<label>Units</label>
<input name="units" type="text" onChange={(event) => changeUnits(event.target.value)}></input>
</span>
<span className="price">
<label>Price</label>
<input name="price" type="text" onChange={(event) => changePrice(event.target.value)}></input>
</span>
</div>
<div className="recordBtn">
<button onClick={(event) => calculateTotal()}>Record</button>
</div>
</div>
<div className="purchasedbooks">
<h3>Purchased book:</h3>
<table>
<tr>
<th>Item no</th>
<th>Books</th>
<th>Units</th>
<th>Price</th>
</tr>
{
//currentRecord.map(({ currentBook, currentUnits }) => (
<tr>
<td>1.</td>
<td>{currentBook}</td>
<td>10</td>
<td>250</td>
</tr>
// ))
}
</table>
</div>
</div>
</div>
);
}
export default App;
Several changes have been made in the sandbox link
Calculate the total when click record as asked in the question
Add some checking when user press the record button. Three inputs need to be filled in.
The input type should be number but not text since it may need to NaN if user enter string in the input.
Implementing a button to reset all the record.
Use map for rendering currentRecord
It looks like your map should look like this:
{currentRecord.map(item => (
<tr>
<td>1.</td>
<td>{item.currentBook}</td>
<td>{item.units}</td>
<td>{item.price}</td>
</tr>
))
}

Getting selected item of ng repeat on a datalist

I'm using a array iteration to know which is the selected option. I'm insterested on id atribute of result. is there other way?
<input type="text" list="products" ng-model="query" />
<datalist id="products">
<option value="{{result.name}}" ng-repeat="result in results" >
</datalist>
...
$scope.search = function (query) {
$scope.results.forEach(function (result) {
if (result.name === query) {
// code here
}
}
}
...
Try this:
<datalist id="products">
<option value="{{result.name}}" ng-selected="query.id == result.id" ng-repeat="result in results" >
</datalist>

Resources