Skip to content

Commit 12885ab

Browse files
authored
Merge pull request #25 from josefdolezal/patch-1
Cleanup after an effect before executing a new one
2 parents 9880282 + b311aa6 commit 12885ab

File tree

2 files changed

+56
-3
lines changed

2 files changed

+56
-3
lines changed

Sources/Hooks/Hook/UseEffect.swift

+3-3
Original file line numberDiff line numberDiff line change
@@ -63,18 +63,18 @@ private struct EffectHook: Hook {
6363
}
6464

6565
func updateState(coordinator: Coordinator) {
66+
coordinator.state.cleanup?()
6667
coordinator.state.cleanup = effect()
6768
}
6869

6970
func dispose(state: State) {
71+
state.cleanup?()
7072
state.cleanup = nil
7173
}
7274
}
7375

7476
private extension EffectHook {
7577
final class State {
76-
var cleanup: (() -> Void)? {
77-
didSet { oldValue?() }
78-
}
78+
var cleanup: (() -> Void)?
7979
}
8080
}

Tests/HooksTests/Hook/UseEffectTests.swift

+53
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ import XCTest
44
@testable import Hooks
55

66
final class UseEffectTests: XCTestCase {
7+
enum EffectOperation: Equatable {
8+
case effect(Int)
9+
case cleanup(Int)
10+
}
11+
712
func testEffectWithoutPreservationKey() {
813
var effectCount = 0
914

@@ -98,6 +103,30 @@ final class UseEffectTests: XCTestCase {
98103
XCTAssertEqual(cleanupCount, 2)
99104
}
100105

106+
func testEffectOperationsOrder() {
107+
var operations: [EffectOperation] = []
108+
var step = 1
109+
110+
let tester = HookTester {
111+
useEffect(.preserved(by: step)) {
112+
let effectStep = step
113+
operations.append(.effect(effectStep))
114+
return { operations.append(.cleanup(effectStep)) }
115+
}
116+
}
117+
118+
XCTAssertEqual(operations, [.effect(1)])
119+
120+
step += 1
121+
tester.update()
122+
123+
XCTAssertEqual(operations, [.effect(1), .cleanup(1), .effect(2)])
124+
125+
tester.dispose()
126+
127+
XCTAssertEqual(operations, [.effect(1), .cleanup(1), .effect(2), .cleanup(2)])
128+
}
129+
101130
func testLayoutEffectWithoutPreservationKey() {
102131
var effectCount = 0
103132

@@ -190,4 +219,28 @@ final class UseEffectTests: XCTestCase {
190219
tester.dispose()
191220
XCTAssertEqual(cleanupCount, 2)
192221
}
222+
223+
func testLayoutEffectOperationsOrder() {
224+
var operations: [EffectOperation] = []
225+
var step = 1
226+
227+
let tester = HookTester {
228+
useLayoutEffect(.preserved(by: step)) {
229+
let effectStep = step
230+
operations.append(.effect(effectStep))
231+
return { operations.append(.cleanup(effectStep)) }
232+
}
233+
}
234+
235+
XCTAssertEqual(operations, [.effect(1)])
236+
237+
step += 1
238+
tester.update()
239+
240+
XCTAssertEqual(operations, [.effect(1), .cleanup(1), .effect(2)])
241+
242+
tester.dispose()
243+
244+
XCTAssertEqual(operations, [.effect(1), .cleanup(1), .effect(2), .cleanup(2)])
245+
}
193246
}

0 commit comments

Comments
 (0)