The heading tag should say "Marco " to begin with and the button shows "polo". onClick they should interchange. I'm using useState and an array to do the job. They should keep interchanging. But after a round, they repeat. I guess on the third round. I cannot understand why this is happening.
import React, { useState } from "react"; import "../styles/App.css"; const App = () => { let arr = ["Marco", "Polo"]; const [input, setInput] = useState(arr[0]); const [inputButton, setInputBUtton] = useState(arr[1]); const changethis = () => { // console.log("Clicked"); // console.log(arr); let temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; console.log(arr); setInput(arr[0]); setInputBUtton(arr[1]); }; return ( <div id="main"> <h1 id="marco-polo">{input}</h1> <button id="marco-polo-toggler" onClick={changethis}> {inputButton} </button> </div> ); }; export default App;
when I console log my array I'm getting like this.
(2) ['Polo', 'Marco']
(2) ['Polo', 'Marco']
(2) ['Marco', 'Polo']
(2) ['Polo', 'Marco']
(2) ['Polo', 'Marco']
(2) ['Marco', 'Polo']
(2) ['Polo', 'Marco']