0

I have a hand full of json objects I need to load into a react native app. I couldn't find much documentation on how import sample from '../data/Sample.json'; imports. I will only need to load 1 file depending on what the user selects and I am not sure if I just import all 12 files (1mb total) if that will be more impactful on performance than I need. Is there a way I can selectively load a json file depending on state or user input?

4
  • Have you tried require() for importing it? You could set a variable string to the file you need programmatically and call require(pathToRequiredFile) to load it. However, require caches your files for future use, so keep that in mind of you use it. Commented Oct 23, 2018 at 3:34
  • Im not sure how that would work, could you show me an example or point me in the direction of the documentation on require? Commented Oct 23, 2018 at 3:37
  • How will you decide which of the 12 files needs to be imported? Based on some variable, etc? Commented Oct 23, 2018 at 4:17
  • Yes, a known variable. 1 of 12. Commented Oct 23, 2018 at 5:26

1 Answer 1

1

Put the links to the JSON files in an array and use require() as needed:

links = [
  'link_to_file_1.json',
  'link_to_file_2.json',
  // and so on...
];

loadMyFile = (index) => {  // Call this function with required index of list

    if (index)
    {
      let fileUrl = require(links[index]);

      // parse file, perform required actions ...
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, ill try this out. Looks promising.
Pops an error: "calls to 'require' expect exactly 1 string literal argument, but this was found 'require(links[index])'
How are you calling the method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.