javascript / intermediate
Snippet
Reactive Data Validation with Proxy
The Proxy API allows you to wrap an object and intercept operations like property assignment. This is powerful for building reactive systems or adding a validation layer directly to your data models.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const userSchema = {set(target, key, value) {if (key === 'age' && (typeof value !== 'number' || value < 0)) {throw new Error('Age must be a positive number');}target[key] = value;return true;}};const user = new Proxy({}, userSchema);
nextjs
Breakdown
1
set(target, key, value)
A 'trap' that intercepts every attempt to set a property on the object.
2
throw new Error(...)
Prevents invalid data from being written to the original object.
3
new Proxy({}, userSchema)
Creates the proxy instance using the original object and the handler.