Home > Enterprise >  Why does an array reverse itself outside of a useEffect?
Why does an array reverse itself outside of a useEffect?

Time:02-06

There is an array called recent that contains the values of an input when a form is submitted. Let's say the array contains the values 'London' and 'Paris'. Inside the useEffect, the array would return [London, Paris] as it should. However, outside the useEffect, the array would return the values [Paris, London] - the reverse.

At first, I thought that it was due to a second array list that was assigned the reverse of the recent array inside the useEffect, but this is not the case as the recent array still returns the values correct order after the reverse is assigned to list. The recent array is reassigned to list every time a new value is added to recent so that list is always the reverse of recent.

How do I fix this?

const [recent, setRecent] = useState([]);
const [reverse, setReverse] = useState(true); // says whether to reverse list or not
const [list, setList] = useState();

const RecentSearches = () => {
  useEffect(() => {
    if (reverse) {
      console.log(recent, "before reverse"); // returns ['London', 'Paris']
      setList(() => recent.reverse()); // reverses recent
      setReverse(false); // does not reverse list every time the function runs - only reverses it once
      console.log(recent, "after reverse"); // returns ['London', 'Paris']
      console.log(recent[0], "first item"); // returns 'London'
    }
  }, []);

  let searches;
  console.log("============");
  console.log(recent); // returns ['Paris', 'London']
  console.log(recent[0], "first item"); // returns 'Paris' 
  console.log("---------");
  console.log(list); // returns ['Paris', 'London']
  console.log("============");

  if (list) {
    searches = list.map((value, index) => ( <
      button type = "submit"
      form = "form"
      key = {
        index
      }
      onClick = {
        () => setSearch(value)
      }
      onm ouseEnter = {
        () => setSearch(value)
      }
      onm ouseLeave = {
        () => setSearch("")
      } > {
        value
      } <
      i className = "fa-solid fa-chevron-right" > < /i> < /
      button >
    ));
  } else {
    searches = "";
  }
  return searches;
};

const [search, setSearch] = useState(""); // value in the input

const handleSubmit = async event => {
  console.log("form submitted");
  event.preventDefault();
  setRecent([...recent, search]); // adds search value to end of recent array
  setReverse(true); // means that list will be set to reverse of recent with the new value
  ...
};

CodePudding user response:

Array.reverse is destructive which means that by doing recent.reverse() you're actually réversible recent. You should do instead

setList([...recent].reverse()]

So you're not changing directly recent

  • Related