I mistakenly thought I would need to proxy the array as nested but I was incorrect. The correct answer was just a simple array utilizing get()
to proxy the array and all it's content.
I have a site that gets data through a function that creates an array. The problem is that array is nested whenever it gets to the site. This isn't an issue for the site since it can use that nested array to create a table. However, I'm trying to set up a proxy to monitor that array so that whenever something changes in the array on the backend, the site table will update.
The array pulls more data than I am showing here but this is what the array looks like:
//each table has a checkbox column
{
'0' : {
'Service': 'On Site',
'Authorization': '4/15/22',
'Client Waiver Due' : '4/15/22',
'90 Day Progress' : '1' //checked
},
'1' : {
'Service': 'Off Site',
'Authorization': '7/15/22',
'Client Waiver Due' : '7/15/22'
'90 Day Progress' : '0' //unchecked
},
I'm trying to proxy the Service
, Authorization
, Client Waiver Due
and 90 Day Progress
every time there is a change on the backend. I'm fairly new to programming so I apologize if the answer is simpler than I think it is.
I tried the answer provided on in the question How to use javascript proxy for nested objects but I keep getting undefined
or some error is spat out in the console.
I think it might be relevant so I should mention that each value will be capitalized and some will have spaces in them so proxy.0.Service
and proxy.0.Client Waiver Due
are most likely part of the issue I am having.
edit: Here is what the code looks like that throws errors.
const handler = {
get(target, key) {
if (key == 'isProxy')
return true;
const prop = target[key];
// return if property not found
if (typeof prop == 'undefined')
return;
// set value as proxy if object
if (!prop.isProxy && typeof prop === 'object')
target[key] = new Proxy(prop, handler);
return target[key];
},
set(target, key, value) {
console.log('Setting', target, `.${key} to equal`, value);
// todo : call callback
target[key] = value;
return true;
}
};
const test =[
{ Client: 'Jon Doe',
Service: 'Off Site',
'90 Day Review': '6/13/22',
'Day Review Completed?': '1' },
{ Client: 'Jane Smith',
Service: 'On Site',
'90 Day Review': '7/11/22',
'Day Review Completed?': '0' }
]
const proxy = new Proxy(test, handler);
console.log(proxy);
console.log(proxy.string); // "data"
proxy.string = "Hello";
console.log(proxy.string); // "Hello"
console.log(proxy.object); // { "string": "data", "number": 32434 }
proxy.object.string = "World";
console.log(proxy.object.string); // "World"