Reputation: 272134
const Data = {
teachers: {
size: 15,
num: 4,
color: 'blue'
}
}
const person = {
name: 'John',
group: Data.teachers, // This is Default. If I do this, the entire teachers tree gets cached. Later, teachers tree changes, this is unusable.
group: () => Data.teachers // I want to do this, so that it fetches fresh data. But, see below for the LJSON problem...
}
I understand that JSON.stringify does not support functions.
I've looked into LJSON (https://github.com/MaiaVictor/LJSON). LJSON does not fix the problem. They also cache Data.teachers, as is. When using LJSON, if Data.teachers
changes, then calling group()
will not get the latest. It will return the old tree.
(Current stack is React-Native, with AsyncStorage, using JSON.stringify/parse.)
Upvotes: 0
Views: 127
Reputation: 8329
Have you tried the toString()
method of a Function
& eval
?
const fn = (arg) => {
console.log('function:', arg)
}
fn('yes, it works')
const jsonFn = JSON.stringify(fn.toString()) // now its a JSON.stringified string
const newJsonFn = JSON.parse(jsonFn) // parsing it back from JSON to string
const newFn = eval(newJsonFn) // eval!!!
newFn('yes, it works again')
Yes, this snippet solves your problem. But don't forget that eval
is a dangerous tool: about eval security issues.
Upvotes: 1