Reputation:
I am using React.js to create the front-end side of a web application that can control home appliances.
What I want to achieve is I have a slider (LightSliderBar.js) that can change the brightness of the light When I move the slider, for some reason the slider almost freezes and I can't move it I want it to move smoothly.
DiscoverOffice.js
const DiscoverOffice = () => {
const [light, setLight] = useState([]);
const getDevices = async(data) => {
await axios.get('xxx.com',
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
setLight(result.data.attributes.light);
})
.catch(err => {
console.log(err);
});
}
return (
{light.map((item,i) =>
<LightSliderBar item={item}/>
)}
);
}
export default DiscoverOffice;
LightSliderBar.js
const LightSliderBar = ({ item }) => {
const cookies = new Cookies();
const entity_id = item.entity_id;
const [light, setLight] = useState([]);
const [brightness_value, setBrightnessValue] = useState(item.brightness);
const lightOn = async(data) => {
console.log("Body sent to server", {
entity_id: entity_id,
brightness: brightness_value
})
await axios.post('xxx.com',
{
entity_id: entity_id,
brightness: brightness_value
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log('Turn on!');
getDevices();
})
.catch(err => {
console.log('Turn on Missed!');
});
}
const getDevices = async(data) => {
await axios.get('xxx.com',
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log(result.data)
setLight(result.data.attributes.light);
setBrightnessValue(result.data.attributes.light.filter(c => c.entity_id === entity_id).map((item,i) => item.brightness)[0]);
})
.catch(err => {
console.log(err);
});
}
useEffect(() => {
getDevices();
}, []);
return (
<div>
<input className="range-input" type="range" name="speed" min="0" max="100" id="slider"
value={brightness_value} onChange={lightOn} style={{ background: gradient, }}></input>
</div>
);
};
export default LightSliderBar;
Upvotes: 0
Views: 310
Reputation: 886
The problem as mentioned in your comments is most likely the fact, that you are sending an request with every change emited on your input. This is usually solved by delaying request to the start of longer pause.
let changeTimeout
const onChangeHandler = () => {
clearTimeout(changeTimeout)
changeTimeout = setTimeout(() => {
lightOn()
}, 300)
}
If you change your onChange function to this it should solve it.
Explanation
You have a timer, which resets with every change and at the end of that timer is your request. This means that the request is called only if that timer had time to end. In this case it means after 300ms.
Upvotes: 0