I want to increase each item in sliderValues
+20 when clicking Increase Volume.
import React, { useState, useRef } from 'react';
export const App = ({ name }) => {
const [sliderValues, setSliderValues] = useState([50, 50, 50, 50, 50]); // Initial slider values
const audios = [
{ src: '/fire.mp3', icon: '\f06d' },
{ src: '/crickets.mp3', icon: '\e4d0' },
];
const increaseVolume = () => {
audios.forEach((audioRef, index) => {
setSliderValues((prevValues) =>
prevValues.map((prevValue) => {
console.log(prevValue); // Log the previous value
return prevValue + 20;
})
);
});
};
return (
<div>
<button onClick={increaseVolume}>Increase Volume</button>
{/* Displaying the slider values */}
<ul>
{sliderValues.map((value, index) => (
<li key={index}>{value}</li>
))}
</ul>
</div>
);
};
But right now, the items are increasing by +40. I think it’s because there are two loops (forEach
and map
) and the +20 is being applied twice. But I’m not very sure how to fix this. Any suggestions?
Current output:
90
90
90
90
90
Desired output:
70
70
70
70
70
Working code on StackBlitz.
2
Answers
You have nested loops (
forEach
andmap
), and the increase is being applied twice. You can directly access the corresponding index in themap
function.Working Stackblitz
There is no need for the first
forEach
since you’re not doing anything with the audio’s here.Change the
increaseVolume
function to:Updated Demo: