Created
July 7, 2020 17:27
-
-
Save mbrandonw/b1628c0d8d711f96e4b4dd1b522321d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@State var isFavorite = false | |
var body: some View { | |
FavoriteComponent(id: 42, isFavorite: self.$isFavorite) | |
} | |
} | |
// A shareable "favoriting" component. Just instantiate it with the id | |
// of the thing you want to favorite, and a binding to the boolean | |
// representing its favorited state, and it will take care of the rest: | |
// | |
// * It will optimistically toggle the favoriting state | |
// * It will make an API request to try to favorite | |
// * If the favoriting fails it will revert the favorited state | |
struct FavoriteComponent: View { | |
let id: Int | |
@Binding var isFavorite: Bool | |
var body: some View { | |
Button(action: { | |
// Optimistically toggle the favorited state | |
self.isFavorite.toggle() | |
// Make an API request to your server to tell it to favorite the item | |
// with id `self.id`. | |
URLSession.shared | |
.dataTask(with: URL(string: "https://www.site.com/item/\(self.id)/favorite")!) { _, _, error in | |
// If we got an error then revert the state of the component | |
if error != nil { | |
self.isFavorite.toggle() | |
} | |
}.resume() | |
}) { | |
Image(systemName: self.isFavorite ? "heart" : "heart.fill") | |
.foregroundColor(.blue) | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment