Reputation:
Here's my code:
reorder = (dragItemId, startIndex, endIndex) => {
//find the element in the this.state.feladatok which has the same id i pass with reorder
const dragElem = this.state.feladatok.find(elem => dragItemId === elem.id);
//find all elements which has the same szid which dragElem has,
//then sort them. The lista is an array, a piece of this.state.feladatok
const lista = this.state.feladatok.filter(listaelem => listaelem.szid === dragElem.szid).sort((a, b) => a.rang - b.rang);
//i need here to remove lista from this.state.feladatok
const [removed] = lista.splice(startIndex, 1);
lista.splice(endIndex, 0, removed)
//now i need to put it back
fetch('http://localhost:3001/rangvalt', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
lista: lista
})
})
.then(res => res.json())
.then(ujlista => this.setState({feladatok: ujlista}))
//because waiting for this response is too slow
.catch(err => console.log(err)) ;
}
Here's a function that i use in react, and works well, but waiting for the response of the server cause UX problems, what i can (i think) easily solve with updating not just server side, but immediately in client side. The main problem here is removing. So how to expand the methods of lista
to not just get, and sort, but remove them with setState()
(or something else)?
Upvotes: 1
Views: 160
Reputation: 1891
This is how you would add the element to endIndex
. Unless I'm misunderstanding the question, you shouldn't need startIndex
.
const dragElem = this.state.feladatok.find(elem => dragItemId === elem.id);
// Remove dragElem from array
const lista = this.state.feladatok.filter(listaelem => listaelem.szid === dragElem.szid).sort((a, b) => a.rang - b.rang);
// Insert dragElem into lista at index endIndex
const newLista = [...lista.slice(0, endIndex), dragElem, ...lista.slice(endIndex)];
this.setState({feladatok: newLista});
Upvotes: 1