Skip to content
This repository has been archived by the owner on Oct 17, 2024. It is now read-only.

Duplicate items in List #47

Closed
iDevPro opened this issue Aug 21, 2024 · 1 comment
Closed

Duplicate items in List #47

iDevPro opened this issue Aug 21, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@iDevPro
Copy link

iDevPro commented Aug 21, 2024

Describe the bug

Hello @david-swift
I found strange issue with List, the Item is duplicated

To Reproduce

I want get "load more" functionality,
after load next portion of content i modify list like this:

@State var items: [Item] = []

func loadMore() {
    
    // fetch and decode here
    
    Idle {
             var items = self.items
             let loadMoreIndex = items.lastIndex(where: { $0.id == "load-more" })! // ! for simplify construction here 
             self.items.insert(contentsOf: fetchedItems, at: loadMoreIndex) // for insert at the end but before load more item
    }
}

Current behavior:

  • items contains one object with id "load-more"
  • list contains two view with text "Load more..."

Expected behavior

  • items contains one object with id "load-more"
  • list contains one view with text "Load more..."

Additional context

No response

@iDevPro iDevPro added the bug Something isn't working label Aug 21, 2024
@david-swift
Copy link
Member

david-swift commented Aug 25, 2024

I'm not able to reproduce this and it looks like unexpected behavior, so I'd be very happy if you could provide more details about the situation it occured.

As far as I understand your idea, what you're trying to accomplish could be accomplished in a cleaner way using a computed property combined with the state property:

@State private var items: [Item] = []

var allItems: [Item] {
    items + [id: "load-more")]
}

var view: Body {
    List(allItems) { item in
        switch item.id {
            case "load-more":
                // Load more view
            default:
                // Other views
        }
    }
}

func loadMore() {
    // ...
    items += fetchedItems
    // ...
}

It may help looking at #37 (comment) for more information about state. In general, if state management is complex, there's probably a simpler, more elegant solution. You can always open a discussion if you have questions! And I'll definitely improve the docs to mention those concepts at some point.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants