Bug delete el on array

Viewed 83

My function is constantly removing the last element of the array, although I added a check by index

DelCategory it's popup, useState del responsible for rendering the popup

When clicking on DelCategory onClick = {delCatC}, the selected category was deleted

Thanks in advance

BlockListAdmin

function BlockListAdmin() {
    const category = useSelector(state => state.newcat.category); // * Take category from redux store
    console.log(category)
    const dispatch = useDispatch()


    const DelCategoryC = (id) => {
        dispatch(delCat(id))
    }


    const [del, setDel] = useState(false);
    const delCatT = () => {
        setDel(!del)
    }

    return (
        <>
            <div className='container'>
                {category.map((objectCategory) => {
                    return (
                        <div className={style.blockList} key={Math.random().toString()} style={{ borderTop: `3px solid ${objectCategory.color}` }}>
                            <div className={style.blockListHead}>
                                <h4 className={style.blockTitle}>
                                    {objectCategory.name}
                                </h4>
                                <button className={style.btnDown}>
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                        xmlns="http://www.w3.org/2000/svg">
                                        <path d="M6 9L12 15L18 9" stroke="white" stroke-width="1.5"
                                            stroke-linecap="round" stroke-linejoin="round" />
                                    </svg>
                                </button>
                                <button className={style.btnUp}>
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                        xmlns="http://www.w3.org/2000/svg">
                                        <path d="M6 15L12 9L18 15" stroke="white" stroke-width="1.5"
                                            stroke-linecap="round" stroke-linejoin="round" />
                                    </svg>
                                </button>
                                {/* тут было */}
                                <button className={style.btnClose} onClick={delCatT}>
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                        xmlns="http://www.w3.org/2000/svg">
                                        <path d="M18 6L6 18" stroke="white" stroke-width="1.5" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                        <path d="M6 6L18 18" stroke="white" stroke-width="1.5" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                    </svg>
                                </button>
                            </div>
                            {/* {
                               objectCategory.list.lenght ? <ul className={style.list}>
                                {objectCategory.list.map((item) => {
                                    return <BlockItemAdmin title={item.title} about={item.about} img={item.imgLink}
                                                           url={item.url} key={Math.random().toString()}/>;//? replace key;
                                })}
                            </ul> : <NewCategory/>
                           }  */}
                            <ul className={style.list}>
                                {objectCategory.list.map((item) => {
                                    return <BlockItemAdmin title={item.title} about={item.about} img={item.imgLink}
                                        url={item.url} key={Math.random().toString()} />;//? replace key;
                                })}
                            </ul>
                            {del ?
                                <DelCategory id={objectCategory.id} setActiveWindow={setDel} /> : null}
                        </div>
                    )
                })}
            </div>
        </>
    )
}
export default BlockListAdmin;

DelCategory

function DelCategory({id, setActiveWindow}) {


    const dispatch = useDispatch()

    const delCatC = (e) => {
        e.preventDefault()
       setActiveWindow(false)
        dispatch(delCat(id))
    }

    return (
        <div className={style.form}>
            <form className={style.AddBookmark}>
                <div className={style.formTitle}>
                    Удаление категории
                </div>
                <p className={style.text}>Вы уверенны, что хотите удалить эту категорию?
                    Все закладки из этой категории также будут удалены</p>

                <div className={style.btnGroup}>
                    <button className={style.addBtn} type="submit" onClick={delCatC}>Уалить категорию</button>
                    <button className={style.cancelBtn}>Отмена</button>
                </div>
                <button className={style.formBtnClose}>
                    <svg width="20" height="20" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 4L4 12" stroke="#696969" stroke-width="2" stroke-linecap="round"
                              stroke-linejoin="round"/>
                        <path d="M4 4L12 12" stroke="#696969" stroke-width="2" stroke-linecap="round"
                              stroke-linejoin="round"/>
                    </svg>
                </button>
            </form>

        </div>
    )
}

export default DelCategory;

action

export const delCat = (id) => ({
  type: 'DEL_CATEGORY',
  payload: { id },
})

reducer

const initialState = {
    category: [
        {
            id: 1,
            name: "Изброное",
            color: "#5236C1",
            list: [
                {
                    title: "Яндекс.Почта",
                    about: "Сервис с бесплатными иконками на любой вкус и цвет и есть немного платных. Но норм.",
                    imgLink: 'https://www.google.com/s2/favicons?domain=https://mail.yandex.ru/',
                    url: 'https://www.yandex.ru'
                },
            ]
        },
    ]
};
const delCat = (state, payload) => {
    const { id } = payload
    const idx = state.category.findIndex((el) => el.id === id)
    let pastState = state.category.slice(0, idx)
    let futureState = state.category.slice(idx + 1)
    let newState = [...pastState, ...futureState]
    return {
        ...state,
        category: newState,
    }
}
const newcat = (state = initialState, action) => {
    switch (action.type) {
        case 'DEL_CATEGORY':
            return delCat(state, action.payload)
        default:
            return state;
    }
};
export default newcat;

My friends, fewer bugs for you

1 Answers

The problem was that when rendering, the id was overwritten with the id of the last element. Thus, id was assigned the number of the last element. To avoid this, as an option, you should create a useState and put the id of a specific element in it.

Update

BlockListAdmin

//create state
    const [id, setId] = useState(null);
//create func
     const takeId = (id) => {
        setId(id)
        setDel(!del)
    }

 <button className={style.btnClose} onClick={() => takeId(objectCategory.id)}>

 {del ?<DelCategory  setActiveWindow={setDel} elDelId={id}/> : null}

DelCategory

 const delCatC = (e) => {
        e.preventDefault()
        setActiveWindow(false)
        dispatch(delCat(elDelId))
    }
Related