Home > Back-end >  How i can refresh this function on started value
How i can refresh this function on started value

Time:11-22

Hi! i have a problem with my state in React, I have two onm ouse functions, the first one is to add an element and the second one is to delete, unfortunately the second one does not delete and the added element 'opacity' is rendered.

    let menuItems = ['Tasks', 'Issues', 'Files', 'Raports']
    const [item, setItem] = useState(menuItems)
    const handleSpace = (id) => {
        menuItems.splice(id, 0, 'opacity')
        setItem([...item])
    }
    const restart = () => {
        menuItems = ['Tasks', 'Issues', 'Files', 'Raports']
        setItem([...item])
    }

    return (
        <>
            <div className="dashboard" style={slide.flag ? {left: '-105%'} : {left: '0%'}}>
                <div className="dashboard__nav">
                    <ul className="dashboard__nav-list">
                        {item.map((item, id) => {
                            return <li className="dashboard__nav-item" key={id} onm ouseOver={() => handleSpace(id)} onm ouseLeave={restart}>{item}</li>
                        })}
                    </ul>
                </div>
                <div className="dashboard__array">
                    {tasks.map((task, id) => {
                    return (
                        <div className="dashboard__array-item" key={id}>
                            <div className="dashboard__array-item-header">
                                <p className="dashboard__array-item-header-title">{task}</p>                           
                                <button className="dashboard__array-item-header-cancel">
                                    <FontAwesomeIcon icon={faCancel} />    
                                </button>  
                            </div>
                            <div className="dashboard__array-item-main">
                                <p className="dashboard__array-item-main-description">{descriptionTasks[id]}</p>
                                <p className="dashboard__array-item-main-button">Show More</p>
                            </div>
                        </div>
                    )
                    })}
                </div>
            </div>
        </>
    )

I already created setItem(menuItems), it removed the element 'opacity, but juz it didn't add it a second time

CodePudding user response:

It seems that the two functions might be over complicating the handling of the item state.

Try handle setItem without changing another variable menuItems, so it can be used as a reset value at anytime.

Example:

const menuItems = ["Tasks", "Issues", "Files", "Raports"];

const [item, setItem] = useState(menuItems);

const handleSpace = (id) =>
  setItem((prev) => {
    const newItems = [...prev];
    newItems.splice(id, 0, "opacity");
    return newItems;
  });

const restart = () => setItem(menuItems);

Hope this will help.

  • Related