ollija / react-native-sortable-grid

Drag-drop-sortable grid view for react native
MIT License
441 stars 173 forks source link

Is there an example where item values change on reorder? #62

Open GDM95 opened 4 years ago

GDM95 commented 4 years ago

I'm using the library to create a photo grid that supports adding, deletion, and reordering of photos. I am storing all of my data in a redux store from which the grid is populated. Adding and deleting photos works fine, but I'm having some trouble with rearranging photos.

Here is the data structure I'm using for my photos ( in Redux reducer):

photos: {"0" : null, "1" : null, "2" : null, "3" : null, "4" : null, "5" : null}

This is my component code so far:

` const PhotoUpload = ({ navigation }) => {

// Redux hooks
const photos = useSelector(state => state.user.user.photos);
const dispatch = useDispatch();

// function to reorder the images
reorderImages = (itemOrder) => {
  const temp = {}
  const photosCopy = {...photos}

  const array = itemOrder.itemOrder

  for (let index = 0; index < array.length; index++) { 
     let e = array[index]
     let key = e.key
     let order = e.order

     temp[order] = photosCopy[key]
  }

  dispatch(setStorePhotos(temp));
}

return (
 <>
    <SortableGrid
    // ... other props ommitted
    onDragRelease       = { (itemOrder) => reorderImages(itemOrder) }
    onDragStart         = { (photo) => console.log("Block: ", photo, " is being dragged now!") } >

    {
        Object.keys(photos).map((key) => 

           <View key={ key } onTap={() => this.pickSingle(true, false, key)} >
               <Image defaultSource={ require('./default-avatar.png') } source={ getPhoto(key) } />
               //... add/delete buttons ommitted
           </View>

        )
    }
    </SortableGrid>
 </>

) }`

I am testing adding two images and then swapping their positions. After the reorderImages function returns, I log all of the filenames in the photos object. Everything is in the right order:

0 IMG_0002.JPG

1 IMG_0001.JPG

2 null

3 null

4 null

5 null

The images in the Grid are still in the original order though:

Screen Shot 2020-01-08 at 4 14 35 PM

And when I go to delete the first image, it thinks I'm clicking the second image, so it just sets the first image to null and doesn't slide the other image to the left (part of my deletion logic).

Screen Shot 2020-01-08 at 5 01 16 PM

I don't know whether I have a logical error or if this is some interaction between redux and the SortableGrid but I've already spent a significant amount of time working on this and I need some fresh eyes.

luaninfocast commented 4 years ago

I'm facing the same problem as you, I record the history in the session when I close the app and reopen the order is not correct