i have a input field and slider which has range between 1 to 100.
since i have toggle switches and drop downs i keep onChange events for each field instead of submit button including for slider also.
but i am facing an issue if i try to change slider from 1 to 50 all values upto 50 are submitting using onChange and i tried to use onSlideEnd but it showing old value (ex: showing 1 when selecting 50 from 1 and showing 50 when selecting 20 from 50).
i want it like while changing from 1 to 50 only 50 should send to back end from handleSubmit
i tried this code but not working please help
import React, { useEffect, useState } from 'react';
import { Slider } from "primereact/slider";
import { InputText } from "primereact/inputtext";
//some imports
const Config = () => {
const [factorvalue, setFactorValue] = useState(1);
const [isSliderDragging, setIsSliderDragging] = useState(false);
useEffect(() => {
fetchConfig();
}, []);
const fetchConfig = async () => {
try {
// this is used to get config value from backend to set in front
const response = await Service.getMaliciousFactorConfig();
if (response) {
const maliciousFactorValue = response[0].maliciousFactor || 1;
setFactorValue(maliciousFactorValue);
}
} catch (error) {
console.log(error.message);
}
};
const handleSliderChange = (event) => {
try{
const newValue = parseInt(event.value, 10);
setFactorValue(newValue);
handleSubmit(newValue);
}catch(error){
console.log(error);
}
};
const handleSliderDragEnd = (event) => {
setIsSliderDragging(false);
};
const handleInputChange = (event) => {
const newValue = parseInt(event.target.value, 10);
if (!isNaN(newValue)) {
setFactorValue(newValue);
handleSubmit(newValue);
} else {
setFactorValue("");
}
};
const handleSubmit = async(value) => {
try{
if (value >= 1 && value <= 100) {
setValidationError("");
await ConfigService.setConfig(value);
}
}catch(error){
console.log(error);
}
};
return (
{//demo code}
<div className="displayFlex">
<label htmlFor="factor">Factor:</label>
<div>
<InputText id="factor" value={factorvalue} onChange={handleInputChange} className="w-full" />
<Slider value={factorvalue} onChange={handleSliderChange} onSlideEnd={handleSliderDragEnd} className="w-full" min={1} max={100} />
</div>
</div>
{//some code}
);
};
export default Config;
2
Answers
Debouncing looks like the right solution for you. Read more
A react-hook is available here.
You are thinking in right direction. Follow these steps to get it working (Assuming that you want to submit when
onSlideEnd
fires)fractionValue
, however don’t callhandleSubmit
.handleSubmit
inonSlideEnd