'React beginner using useState and useEffect to rotate an array every second, and reflect the changes in the DOM
I have a problem while rendering back to the DOM the changes happening inside the useEffect. In console.log the array updates every second, and the items are shifting as I want them to. 
But, they are not rendering dynamically back to the DOM. How can I achieve that? My code:
import { useState, useEffect } from "react";
import "./Main.css";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
const App = () => {
let [myList, setMyList] = useState([]);
myList = ["a", "b", "c", "d", "e"];
const Search = () => (
<div className="search__input">
<input type="text" placeholder="Search Band" />
</div>
);
useEffect(() => {
console.log("useEffect");
setInterval(() => {
myList.push(myList.shift());
console.log((myList));
}, 1000);
}
, [myList]);
return (
<div className="main">
<Search />
<ul className="main__list">
{myList.map((item, index) => (
<div className="main__list__item" key={index}>
{item}
</div>
))}
</ul>
</div>
);
}
export default App;
Solution 1:[1]
I managed to get the result that I wanted eventually. My resolve below:
const App = () => {
const [list, myList] = useState(["a", "b", "c", "d", "e"]);
useEffect(() => {
const interval = setInterval(() => {
myList(list.slice(1).concat(list[0]));
}
, 1000);
return () => clearInterval(interval);
});
const [input, setInput] = useState("");
const renderList = () => {
return list.map((item, index) => {
return <li key={index}>{item}</li>;
});
};
const InputField = () => {
return (
<div className="search__input">
<input type="text" placeholder="Search" />
</div>
);
};
return (
<div className="container">
<InputField />
<ul className="main__list">{renderList()}</ul>
</div>
);
};
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Petran Laurentiu |
