My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to define the initial state - the code crashes with an error message stating
Too Many re-renders. React limits the number of renders to prevent an infinite loop.
const [measures, setMeasures] = useState([]);
const [duration, setDuration] = useState([]);
const [word, setWord] = useState('Increasing')
useEffect(() => {
api.get('measures').then(res => {
setMeasures(res.data.measures);
// let a = res.data.measures
});
}, []);
const total = measures.map((duration) => {
return parseFloat(duration.duration);
});
setDuration(total) <<<<<HERE IS CRASHING
const action = () => {
if (word === 'Increasing') {
setWord('Decreasing');
const increasing = () => {
let organiseIncrease = total.sort(function (a, b) {
return (b - a)
});
setDuration(organiseIncrease);
};
increasing()
} else {
setWord('Increasing');
const decreasing = () => {
let organiseDecreasing = total.sort(function (a, b) {
return(a - b)
});
setDuration(organiseDecreasing)
};
decreasing()
}
}
The "total" variable returns numbers like [15, 12, 50]. My goal is to automatically render this array when entering the page and then clicking the button to organize it in either increasing or decreasing order. I attempted to update the hook to:
const [duration, setDuration] = useState([total]);
But it returns: [undefined]. I considered wrapping everything in a function and using Async/Await to fill the hook, but I'm unsure if this approach will be successful. Any suggestions on how to address this issue?