I am displaying my state, which is an array, by iterating through it with the map function. Additionally, I have a button that reverses the array on click.
import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";
import "./App.css";
const App = (props) => {
const [reverse, setReverse] = useState(false);
const [arr, setArr] = useState([]);
useEffect(() => {
let newArr = props.arr;
newArr = newArr.reverse();
setArr(newArr);
}, [reverse, props.arr]);
return (
<div className="App">
<button
onClick={() => {
setReverse(!reverse);
}}
>
Reverse
</button>
{arr.map((e, i) => {
return (
<div key={i}>
<p>{e}</p>
</div>
);
})}
</div>
);
};
App.propTypes = {
arr: PropTypes.array,
};
export default App;
I think it is fairly obvious what I want to do. But it doesn't work for me and I don't know why. I have to click twice to accomplish the first reversion and the weird case emerges in which the array that is rendered and the one shown in the component state by the React dev tools in Chrome do not match.
I cannot explain this behaviour. I am starting to think that it has something to do with the fact that I'm getting the array from the props, but I don't really know. Any ideas?