ref
Overview
Section titled “Overview”The ref
function converts a given value and its nested properties into ref objects recursively, returning a ref object that reflects the structure of the input value.
Getting the Ref Value
Section titled “Getting the Ref Value”You can access the value of the ref object using two methods:
refObj.value
: Accesses the value directly.refObj()
: Invokes the ref object to retrieve its value.
Setting the Ref Value
Section titled “Setting the Ref Value”To update the value of a ref object, you have two options:
refObj.value = newValue
: Sets the value directly.refObj(newValue)
: Invokes the ref object with the new value to update it.
Parameters
Section titled “Parameters”-
value
(optional): Any value that you want to convert into a ref object. The function supports several input types:- Basic types such as numbers, strings, booleans, Date etc.
- ref objects.
- objects
- Array, Map, Set.
null
orundefined
.
Return Value
Section titled “Return Value”The ref
function returns a ref object representing the input value and its nested properties. The specific type of the returned ref object depends on the input value’s type.
- Certain types such as Node, Date, RegExp, Promise, and Error are not recursively converted into ref objects. They are treated as-is and returned as the value of the ref object.
- Arrays and objects are recursively traversed to convert their nested properties into ref objects.
- Symbols are not converted into ref objects, and the original symbols are preserved in the resulting ref object.
- Observers can be attached to the ref object to be notified of changes to its value.
- Every
ref
is ansref
, but not everysref
is aref
.
Example
Section titled “Example”import { ref } from 'regor'
interface Address { city: string state: string}
interface User { name: string age: number address?: Address}
const initialValue: User = { name: 'John', age: 30, address: { city: 'New York', state: 'NY', },}
// create ref from initialValue.// ref call replaces initial value's nested properties with ref objects recursively in place.const myRef = ref<User>(initialValue) // returned type is Ref<User>
// Accessing the ref value using function callconsole.log(myRef()) // Outputs the initial value
// Accessing the ref value using value getterconsole.log(myRef.value) // Outputs the initial value
// Updating the ref valuemyRef().name('Alice') // Modifying the ref value using function callconsole.log(myRef().name()) // Outputs 'Alice'
// Updating the ref value using value using settermyRef().name.value = 'Alice' // Modifying the ref valueconsole.log(myRef().name.value) // Outputs 'Alice'
myRef( ref({ name: 'Alice', age: 35, }),) // Invoking the ref with a new valueconsole.log(myRef().age()) // Outputs 35