M
M
mr jeery2018-02-13 22:46:41
JavaScript
mr jeery, 2018-02-13 22:46:41

How to change property of embedded array object via setState?

Good afternoon, I'm trying to make drag and drop in react using dnd-react
There is an array in state:

const cards = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg',  entries: [{entry: 'nature', idEntry: f1fz2},{entry: wisdom, idEntry:52f55}],
     {id:2 ,name: 'Product B', image: 'pic-002.jpg',  entries: [{entry: 'global', idEntry: z2lz1},{entry: eye, idEntry:71d42}],
     {id:3 ,name: 'Product C', image: 'pic-003.jpg',  entries: [{entry: 'local', idEntry: e34z2},{entry: fridge, idEntry:92f12}],
   ]

This is how I swap cards
updateCardPosition(cardId, afterId) {
    if (cardId !== afterId) {
        let cardIndex = this.state.cards.findIndex((card)=>card.id == cardId);
        console.log('gj', cardIndex)
        let card = this.state.cards[cardIndex];
        let afterIndex = this.state.cards.findIndex((card)=>card.id == afterId);
        this.setState(update(this.state, {
            cards: {
                $splice: [
                    [cardIndex, 1],
                    [afterIndex, 0, card]
                ]
            }
        }));
    }
}

But I also need to swap entry in entries, there are no problems with getting indexes (although something tells me that the code is not very beautiful), but how to make a replacement in setState?
I have a function
updateEntryPosition(Id, afterId) {
    let cardIndex; // индекс карточки в которой меняют положение записи
    let entryIndex; // текущий индекс записи
    let afterIndex; // будущий индекс записи
    this.state.cards.map(card => card.entries.findIndex((entry) => entry.idEntry == Id)).forEach((item,index) => (item>=0) ? [entryIndex, cardIndex]=[item,index] : 0)
    this.state.cards.map(card => card.entries.findIndex((entry) => entry.idEntry == afterId)).forEach(item => (item>=0) ? afterIndex=item : 0)

}

       this.setState(update(this.state, {
    ????
    }));
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question