From 5253d361d63c0613c615d56c130a2a9daec8c497 Mon Sep 17 00:00:00 2001 From: cesarParra Date: Thu, 21 Nov 2024 07:17:03 -0400 Subject: [PATCH] Doc updates --- README.md | 22 +++++++++++++++++++ .../lwc/demoSignals/shopping-cart.js | 4 ++-- src/lwc/signals/__tests__/computed.test.ts | 2 +- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a76700a..9ba0dc5 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,28 @@ export const counterPlusTwo = $computed(() => counterPlusOne.value + 1); Because `$computed` values return a signal, you can use them as you would use any other signal. +## Tracking objects and arrays + +By default, for a signal to be reactive it needs to be reassigned. This can be cumbersome when dealing with objects +and arrays, as you would need to reassign the whole object or array to trigger the reactivity. + +To improve that experience, you can set the `track` flag to true when creating the signal. This will make the signal +reactive to changes in the object or array properties. + +> 📒 Think about this as using the `@track` decorator in LWC properties. It works the exact same way behind the scenes. + +```javascript +import { $signal } from "c/signals"; + +const obj = $signal({ x: 1, y: 2 }, { track: true }); +const computedFromObj = $computed(() => obj.value.x + obj.value.y); + +// When a value in the object changes, the computed value will automatically update +obj.value.x = 2; + +console.log(computedFromObj.value); // 4 +``` + ## Reacting to multiple signals You can also use multiple signals in a single `computed` and react to changes in any of them. diff --git a/examples/demo-signals/lwc/demoSignals/shopping-cart.js b/examples/demo-signals/lwc/demoSignals/shopping-cart.js index 65a86c1..6a4c6c1 100644 --- a/examples/demo-signals/lwc/demoSignals/shopping-cart.js +++ b/examples/demo-signals/lwc/demoSignals/shopping-cart.js @@ -19,9 +19,9 @@ import updateShoppingCart from "@salesforce/apex/ShoppingCartController.updateSh */ // Store each state change in the cart history -export const cartHistory = $signal([], {track: true}); +export const cartHistory = $signal([], { track: true }); $effect(() => { - console.log('cartHistory', JSON.stringify(cartHistory.value, null, 2)); + console.log("cartHistory", JSON.stringify(cartHistory.value, null, 2)); }); let isUndoing = false; diff --git a/src/lwc/signals/__tests__/computed.test.ts b/src/lwc/signals/__tests__/computed.test.ts index 1e8d674..c6918cf 100644 --- a/src/lwc/signals/__tests__/computed.test.ts +++ b/src/lwc/signals/__tests__/computed.test.ts @@ -1,4 +1,4 @@ -import { $computed, $signal, $effect } from "../core"; +import { $computed, $signal } from "../core"; describe("computed values", () => { test("can be created from a source signal", () => {