Home > Software engineering >  combining useState with pop() | Next js
combining useState with pop() | Next js

Time:04-12

I'm trying to update my list using the pop() method. But the page doesn't render, and I couldn't find the issue. I would appreciate any help.

this is my Code

import classes from "./Navigation.module.scss";
import { useState } from "react";

function Navigation(props) {
  const [navItems, setNavItems] = useState([
    { id: 0, link: "HOME" },
    { id: 1, link: "ABOUT" },
    { id: 2, link: "PORTFOLIO" },
    { id: 3, link: "MUSIC" },
    { id: 4, link: "CONTACT" },
  ]);

  const nextHandler = () => {
    let a = navItems;
    a.pop();
    return setNavItems(a);
  };

  return (
    <div className={classes.wrapper}>
      <div onClick={nextHandler} className={classes.nextButton}>
        NEXT
      <div>
      <div className={classes.listWrapper}>
            <div
              className={classes.container}
            >
              <ul>
                {navItems.map((item) => {
                  return <li key={item.id}>{item.link}</li>;
                })}
              </ul>
            <div>
      <div>
    </div>
  );
}

export default Navigation;

So basically, I want to remove the last item when I click the button and want to update the list.

CodePudding user response:

Try it like this:

const nextHandler = () => {
    let a = [...navItems];
    a.pop();
    return setNavItems(a);
};

Otherwise you just copy the reference to the array to a and react will not know that the state has changed.

  • Related