How to update number from an input - reactjs

I am implementing a basic web app in React and I am trying to update an integer from a number type input.
The process is fairly easy but I cannot figure out how to update regarding this process,
let's say we have this hook,
const [fee, setFee] = useState(2); // default value of fee should be 2
handlerFunc() {
// ...
}
<input type="number" onChange={handerFunc} /> which should update the fee
and this <p>Fee is{fee}$</p> should increment one by one after every 500 number is entered in that number type input.
1 for the additional 500 number in the input => 3 fee.
note: The fee should stay 2 until the input number reaches 1999 and for every additional 500 types in the input, the fee should also increment by 1.
How can I implement this handler function regarding this?
Please help.

I've not tried directly if this works as expected but the logic should be this way:
Keep the fee state in synch with the input.
<input type="number" onChange={e => setFee(parseInt(e.target.value,10))} value={fee} />
then store a value in a userRef.
const calculatedFee = useRef(0);
Use useEffect to implement your logic when the fee state change:
useEffect(() => {
if(fee === 500){ // or whatever condition you need
calculatedFee.current = 500 // or a calculated amount.
}
}, [fee]);
display the calculatedFees using the ref value;
<p>{calculatedFee.current}</p>
here is a full example: https://codesandbox.io/s/laughing-star-u4o9x?file=/src/App.js

Related

MUI TextField format input to show numbers and decimals

I'm trying to format the value of the input of this MUI component to show a maximum of 3 numbers following with a maximum of 2 decimals separated by a dot, e.g. 233.99, I want to store this value in a react state called value (const [value, setValue] = useState(0)).
I'm having trouble since I see a lot of approachs to achieve this, but I find it complicated to also keep track if the user already entered the first 3 numbers and not let him enter more while also keeping tack of the decimal values too, since as I said, there should be a maximum of 2 decimals.
I tried regex functions, toFixed js function, and more, but I can't make this work smoothly.
If I understood this correctly, you can achieve this with:
let inp = document.getElementById("input");
inp.addEventListener("keypress", ev => {
ev.preventDefault();
if (!/\d|\./.test(ev.key)) return;
inp.value = /^\d{0,3}(\.\d{0,2})?$/.test(inp.value + ev.key) ? inp.value + ev.key : inp.value;
// update state when value has changed
// if (inp.value != value) setValue(inp.value);
})
<input type="text" id="input">
Alternatively, you can use <input type="text" pattern="^\d{0,3}(\.\d{0,2})?$"> and input.checkValidity() to notify the user on submit.

Is it possible to make a variable dedicated to a certain author Discord.js?

I'm making a store bot and I ran into some SetInterval errors. I want to make it so each variable has the user's id so when I run a different command, it will know which interval to stop. (If that makes sense).
Here is my code:
if(message.content.startsWith(`!open`) {
var cashier1[message.author.id] = function () {
BalanceJSON[message.author.id].bal += 10
Fs.writeFileSync(`./DB/balance.json`, JSON.stringify(BalanceJSON));
}
setInterval(cashier1[message.author.id], 5000);
}
All this code is in a bot.on('message', message => { })
I wanna be able to stop an certain player's interval with clearInterval(cashier1[message.author.id])
The function setInterval returns a unique id which can be used to clear the interval again (See the example for more information).
The solution to your problem is to store the unique id of the interval in some object or database and use that to clear the interval again. See the example code below:
// Create an object to store the intervals.
const cashierIntervals = {};
// Inside your message handler.
// Some dummy if statement for demonstration purpose.
if (message.content === 'setInterval') {
// Create the setInterval and store the unique id in the cashier intervals object.
// You should probably add more checks to see if there is already an interval stored for this author id etc.
cashierIntervals[message.author.id] = setInterval(() => {
BalanceJSON[message.author.id].bal += 10;
Fs.writeFileSync(`./DB/balance.json`, JSON.stringify(BalanceJSON));
}, 5000);
} else if (message.content === 'clearInterval') {
// Clear the interval based on the author id.
// Again, probably add more checks to see if the author id has an interval stored etc.
clearInterval(cashierIntervals[message.author.id]);
// Delete the stored interval entry from the global intervals object.
// Not necessary but it keeps the intervals object small.
delete cashierIntervals[message.author.id];
}
Create an object that takes an id as a key. Your value will be the function you want to interval
Your main file:
const cashier1 = {
// Template for your key:values
'999999999': yourRepeatingFunction(),
}
// Lets say message.author.id returns '999999999'
// Doing setInterval(cashier1[message.author.id], 5000) Will call yourRepeatingFunction()

Svelte - Binding a checkbox to toggle an input value

Using svelte, I want to set the default value of an input based on whether a checkbox is checked or not. The input is used in a drug dosage calculation. The calculation takes an value of weight in kg (k) x the input value.
I also need to have the drug calculation results change when this input value is changed by the checkbox action or when a user changes the input value manually, which doesn't happen currently.
I have been able to implement the input value change when the checkbox is checked but not clear on how to get the calculation to recalculate when the checkbox is checked or the input value is changed manually.
I need some help in integrating the correct input value into my calculation.
Checkbox:
let yes = false;
<input type=checkbox bind:checked={yes} >
Input:
<input value={yes? item.Fdosevalue : item.dosevalue} step={item.dosestep}
min={yes ? item.Fdosemin : item.dosemin} max={yes ? item.Fdosemax : item.dosemax} >
Calculation:
Not sure how to integrate the checkbox change in this calculation.
<span bind:this={k}> {( (k * item.dosevalue)).toFixed(1)} {item.appendvol} </span>
Here is a REPL which will hopefully make it a bit clearer
You can use data binding to accomplish this:
<input bind:value={...} />
You'll just need a place to store the values:
let values = {}
And then you bind to values with a unique key.
<input bind:value={values[item.name]}/>
Make sure to initialize the values dictionary with a default values for each fluid anytime the checkbox changes:
<input type=checkbox bind:value={yes} on:change={handleChange}/>
// initialize default values
function handleChange() {
const entries = fluids.map(item => {
const defaultValue = yes ? item.dosevalue : item.Fdosevalue
return [item.name, defaultValue]
})
values = Object.fromEntries(entries)
}

How to put comma separator in input field in reactjs?

i have a form where i show previous field value in input tag. But, as i put type=number. then my .toLocaleString("en-IN") would'nt work.Also, i want to show comma in INR currency styles. i.e 12,25,789
Following is my code:
<Col lg="2">
<Form.Control
size="sm"
// type="number"
value={temp.originalAmount.toLocaleString("en-IN")}
onChange={this.handlechangevalue.bind(
this,
item,
keys,
index
)}
/>
</Col>
P.S been using react-bootstrap
It's not clear for me where you want to use the comma separated values but you can change between styles with the help of regexp and replace. Something like this:
// 1234567 => 12,34,567
const encode = string => string.match(/(\d{2})(\d{2})(\d{3})/).slice(1).join(',');
// 12,34,567 => 1234567
const decode = string => string.replace(/,/g, '');
(If your input is looks like two digits / comma / two digits / comma / three digits but this can be changed easly ofc.)
Then you can convert the result to number before save into the state and the back to the comma version to display the user.
Also, I would use a text type on the input field an a regexp based validator.
I'm using similar in case of dates.
I've come across this before. What you can do is restrict the type of input in your handlechangevalue function to numbers only. If any other character appears then discard/ignore it.
Something like this:
handlechangevalue(e) {
if( parseInt(e.target.value) !== NaN ) {
this.setState({val: e.target.value});
}
}

Passing props to Field validate gives previous props values

Passing props to Field validate gives previous props values, especially in this case the Quantity. Using this sandbox, follow these steps:
Open sandbox then console
Set Value to 2
Select Quantity to 2
From console, quantity is still set to 1
Press Submit
Pop up has correct values {"amount":4,"quantity":"2","value":"2"}
Change Value to 1 (Now in Console Quantity is 2)
Error message appears
Instead, what should happen:
Step 4 & 7 should have correct Quantity. props has previous value, not updated
Step 8 should not have error because 1 * 2 = 2
Field validation should have current props values
I followed this issue to handle passing props to validate function, but it seems whenever the props changed the component did not get updated and instead will have the previous value.
This one is works for me.
Replace this code with your validateAmount function.
validateAmount = (amount, e) => {
//const { value, quantity } = this.props.formValues
console.log('amount:', amount, 'value:', e.value, 'quantity:', e.quantity)
if (amount < e.value * e.quantity) return 'Nope!'
}
Here second parameter gets the current state of form values. First answer was taken the Redux State.
try this one
validateAmount = (amount) => {
//const { value, quantity } = this.props.formValues
// instead for using values from props ,get values from current state
const { value, quantity } = store.getState().form.simple.values;
console.log('amount:', amount, 'value:', value, 'quantity:', quantity)
if (amount < value * quantity) return 'Nope!'
}

Resources