1

Frontend student here trying to figure out React... I just can't seem to get a hang on these hooks on React. I am trying to setState within the setArray(). This causes an infinite loop in rendering. React won't allow me to do a callback with useEffect(). I can't seem to figure out how to fix this. How can I pass my newly structured array into the state?

   const [yearsArray, setYearsArrayState] = useState([]);    

    timelineData.then((data) => {
                let yearsArrays = [];
                for (let item of data.timelineInfo) {
                    yearsArrays.push(item.year);
                }
                setArray(yearsArrays);
            });

            const setArray = (array) => {
                const passArray = new Set(array);
                const oneOfEachYear = [...passArray];
                setYearsArrayState(oneOfEachYear);
            };
        return (<div>
        {yearsArray.map((item) => (
                                <button
                                    className={style.buttonYear}
                                    onClick={() => {
                                        toggle();
                                        setClickedYear(item);
                                        console.log(clickedYear);
                                    }}  >
                        </button>
         </div>);
rockon_d
  • 1,094
  • 2
  • 8
  • 21
  • You have a typo in your return statement. Is that just a typo into the question or is that in your code? Specifically `yearsArray.map((item) => ( ... )`; – segFault Apr 27 '20 at 22:25
  • How and where do you execute `timelineData` promise? Add the whole component code. – Zekros Admines Apr 27 '20 at 22:33
  • Typo was something that i fixed on my code. Doesnt really effect my code here though. I have a component that does the fetch api. In this component i pull the year keys and values into a new array to render them out in to buttons. I cut away the code that i thought was unnecessary for my question to get rid of confusion. – rockon_d Apr 27 '20 at 22:45

1 Answers1

1

You put timelineData inside a component mount hook

// This effect hook will be executed only once at the component mount
useEffect(() => {
  timelineData.then((data) => {
    let newYearsArrays = [];
     for (let item of data.timelineInfo) {
       newYearsArrays.push(item.year);
     }
     setArray(newYearsArrays);
  });
}, []);
Zekros Admines
  • 302
  • 2
  • 11