Simple example using IfLetStore

Hi everyone.

For some reason I can’t wrap my head around what IfLetStore does and when to use it.

If someone can explain that would be great. Even better if someone can show a simple example.

If there are resources about TCA other then the documentation and point free lessons (already have a subscription). Please let me know

Ps. I’ve looked through the documentation. Still confused and looked through the forum regarding this.

Thanks in advance.

1 Like

Hi @Muhammed9991! There are a few examples in the demo code. Here's a GitHub search that accumulates some: Search · IfLetStore · GitHub

A pretty self-contained example is here: swift-composable-architecture/01-GettingStarted-OptionalState.swift at 0a38f2c860a64a005afeb8a6fe186eb2818c9a3f · pointfreeco/swift-composable-architecture · GitHub

You can see that the store is scoping onto some optional state and passing it to the IfLetStore view. Then the 2 callback closures are invoked depending on that optional state: then is either invoked with a store of non-optional state, or else is invoked with nothing.

There's another example in the Voice Memos demo, which is used for a "current recording" in state depending on if it's nil or not:

Hope these help!

1 Like

Thank you. That makes a lot of sense. I think I was over complicating it.

Sorry bumping the old posts.
TCA is a great, but I cannot find how to listen to state changes and give an action, IfLetStore is awesome and it works really well, but it requires View as return value.
Is there a void version command of IfLetStore ?

Hi @hebbian, it's not clear what you are trying to accomplish and why IfLetStore would be used to solve it. Can you start a new forum post that describes in detail the problem you are having with as much code as possible?

I just want to call function (not a View returning function) in state changes. For example:

IfLetStore(self.store.scope(
	state: \.observedState,
	action: MyViewPresenter.Action.setObservedState(value: )
), then: { _ in
	// myFunctionCallsHere() -> Error `Type '()' cannot conform to 'View'`
        // My silly workaround? 
	Text("")
		.onAppear {
			myFunctionCallsHere()
		}
})

....

func myFunctionCallsHere() {}

It isn't appropriate to execute functions inside the the body of a view. This goes for vanilla SwiftUI too.

The onAppear hack is better, but also leaves you with an empty Text view lying around. You should move this logic to the reducer when the observedState is populated with data.