diff --git a/app/Livewire/Counter.php b/app/Livewire/Counter.php index af6a845..7fbcb86 100644 --- a/app/Livewire/Counter.php +++ b/app/Livewire/Counter.php @@ -31,8 +31,10 @@ public function mount(): void $tracker = Tracker::current(); $this->needsOnboarding = $tracker === null; - $this->count = $tracker === null ? 0 : $tracker->count; - $this->value = $this->count; + + if ($tracker !== null) { + $this->syncFrom($tracker); + } } public function initialise(): void @@ -45,7 +47,7 @@ public function initialise(): void 'count' => $this->value, ]); - $this->count = $tracker->count; + $this->syncFrom($tracker); $this->needsOnboarding = false; } @@ -58,10 +60,8 @@ public function increment(): void } $tracker->increment('count'); - $tracker->refresh(); - $this->count = $tracker->count; - $this->value = $this->count; + $this->syncFrom($tracker->refresh()); } public function edit(): void @@ -83,7 +83,7 @@ public function save(): void $tracker->update(['count' => $this->value]); - $this->count = (int) $this->value; + $this->syncFrom($tracker); $this->editing = false; } @@ -94,6 +94,15 @@ public function cancel(): void $this->editing = false; } + /** + * The tracker is the source of truth; the form input always mirrors it. + */ + private function syncFrom(Tracker $tracker): void + { + $this->count = $tracker->count; + $this->value = $this->count; + } + public function render(): View { return view('livewire.counter')->layout('layouts.app'); diff --git a/resources/views/components/counter-form.blade.php b/resources/views/components/counter-form.blade.php new file mode 100644 index 0000000..0199634 --- /dev/null +++ b/resources/views/components/counter-form.blade.php @@ -0,0 +1,48 @@ +@props([ + 'action', + 'label', + 'submit', + 'id' => 'value', + 'cancel' => false, +]) + +
diff --git a/resources/views/livewire/counter.blade.php b/resources/views/livewire/counter.blade.php index 40222b3..53559f1 100644 --- a/resources/views/livewire/counter.blade.php +++ b/resources/views/livewire/counter.blade.php @@ -3,30 +3,12 @@