Issue overriding dependencies for previews #104
Replies: 4 comments 3 replies
-
I have the same issue. I can only use the previewValue, so I can't have different data in different previews. I've tried many different approaches with |
Beta Was this translation helpful? Give feedback.
-
Hi @nashysolutions, there is not enough information here to know what the problem is. You need to share at least |
Beta Was this translation helpful? Give feedback.
-
Something like this. import Dependencies
import SwiftUI
struct NumberClient {
var getNumber: @Sendable () -> Int
}
extension NumberClient: DependencyKey {
static let liveValue = NumberClient(
getNumber: { 42 }
)
static let previewValue = NumberClient(
getNumber: { 1 }
)
}
extension DependencyValues {
var numberClient: NumberClient {
get { self[NumberClient.self] }
set { self[NumberClient.self] = newValue }
}
}
class FeatureModel: ObservableObject {
var value: Int
init() {
@Dependency(\.numberClient) var numberClient
self.value = numberClient.getNumber()
}
}
struct FeatureView: View {
@State var model = FeatureModel()
var body: some View {
Text("\(model.value)")
}
}
#Preview("default preview dependency") {
FeatureView(
model: FeatureModel()
)
}
#Preview("preview with dependency 2") {
FeatureView(
model: withDependencies {
$0.numberClient = NumberClient(
getNumber: { 2 }
)
} operation: {
FeatureModel()
}
)
}
#Preview("preview with dependency 3") {
FeatureView(
model: withDependencies {
$0.numberClient = NumberClient(
getNumber: { 3 }
)
} operation: {
FeatureModel()
}
)
} If you're using TCA, don't use |
Beta Was this translation helpful? Give feedback.
-
After re-visiting this code, I realised that it was a threading issue on my end. I'm sorry for wasting your time, and greatly appreciate your responses. |
Beta Was this translation helpful? Give feedback.
-
My preview isn't using the mock :(. I don't know what I'm doing wrong.
If I add a preview value here, it works.
Beta Was this translation helpful? Give feedback.
All reactions