0

I have several moderately-size data sets in JSON (a few KB each) that need to be accessed by both my JavaScript controllers (across several different components) and their Apex counterparts, along with the Apex data source for the components' design resource.

What are the best practices for making this data available? I'm currently storing a JavaScript file in a static resource that's loaded by components and simply assigns a block of JSON to an attribute of 'window', but that means I'll need a second copy of the file for the Apex controller to parse, and it's not clear to me that this is the right way to go.

2

The client (Lightning) and the server (Apex) are two separate computing resources. They do need their own copy of the data. Since it's a static resource, you'll save on bandwidth, since you don't need to pass the values back and forth between the client and server. As is, I think you've got a pretty reasonable configuration.


Components in the same namespace share the same window, but if you're developing in an ISV context, you should note that the data won't be available outside of your namespace, in case this matters.

  • This makes sense. Glad I'm on the right track. Do you have thoughts on the best way to structure my static resource so it can be parsed/used by both server and client? With the assignment statement to window.variable I don't believe it's valid JSON for Apex to consume. Is there a way to have JS controllers load data from the static resource without running it as a script using <ltng:require> ? – David Reed Nov 28 '17 at 17:24
  • @sfdcfox This "each component gets its own version of window" statement is incorrect. Even though we get the lockerized window object, component do share the same window object. – Praveen Nov 28 '17 at 17:28
  • @Praveen Ah, all the ones in the same namespace get the same window, at any rate. Components in other namespaces can't see the variables. I'll edit. – sfdcfox Nov 28 '17 at 17:33
  • @DavidReed You're right, it wouldn't be actual JSON, but JavaScript. As far as I can tell, you'll have to go grab the JSON from the server and parse it. You can write an Apex controller method to retrieve the JSON from the static resource or use the Lightning Data Service to get the data without writing Apex Code. Either way, though, you're still going to make a roundtrip to the server to get your JSON at least once. – sfdcfox Nov 28 '17 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.