Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Sources/Hooks/Hook/UseEffect.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,18 @@ private struct EffectHook: Hook {
}

func updateState(coordinator: Coordinator) {
coordinator.state.cleanup?()
coordinator.state.cleanup = effect()
}

func dispose(state: State) {
state.cleanup?()
state.cleanup = nil
}
}

private extension EffectHook {
final class State {
var cleanup: (() -> Void)? {
didSet { oldValue?() }
}
Comment on lines -76 to -78
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: Updating code to willSet is not enough, because effect() was already executed.

var cleanup: (() -> Void)?
}
}
53 changes: 53 additions & 0 deletions Tests/HooksTests/Hook/UseEffectTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import XCTest
@testable import Hooks

final class UseEffectTests: XCTestCase {
enum EffectOperation: Equatable {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Open for naming suggestions 🙏

case effect(Int)
case cleanup(Int)
}

func testEffectWithoutPreservationKey() {
var effectCount = 0

Expand Down Expand Up @@ -98,6 +103,30 @@ final class UseEffectTests: XCTestCase {
XCTAssertEqual(cleanupCount, 2)
}

func testEffectOperationsOrder() {
var operations: [EffectOperation] = []
var step = 1

let tester = HookTester {
useEffect(.preserved(by: step)) {
let effectStep = step
operations.append(.effect(effectStep))
return { operations.append(.cleanup(effectStep)) }
}
}

XCTAssertEqual(operations, [.effect(1)])

step += 1
tester.update()

XCTAssertEqual(operations, [.effect(1), .cleanup(1), .effect(2)])

tester.dispose()

XCTAssertEqual(operations, [.effect(1), .cleanup(1), .effect(2), .cleanup(2)])
}

func testLayoutEffectWithoutPreservationKey() {
var effectCount = 0

Expand Down Expand Up @@ -190,4 +219,28 @@ final class UseEffectTests: XCTestCase {
tester.dispose()
XCTAssertEqual(cleanupCount, 2)
}

func testLayoutEffectOperationsOrder() {
var operations: [EffectOperation] = []
var step = 1

let tester = HookTester {
useLayoutEffect(.preserved(by: step)) {
let effectStep = step
operations.append(.effect(effectStep))
return { operations.append(.cleanup(effectStep)) }
}
}

XCTAssertEqual(operations, [.effect(1)])

step += 1
tester.update()

XCTAssertEqual(operations, [.effect(1), .cleanup(1), .effect(2)])

tester.dispose()

XCTAssertEqual(operations, [.effect(1), .cleanup(1), .effect(2), .cleanup(2)])
}
}