0

Need to import a file depending upon the option selected from the previous screen. Using react-navigation to get the import details.

/* Taking path information from previous screen. */
  const{
    exam_info
  } = route.params;

  /* State to store the data. */
  const[data,setData]=useState([]);

  /* Conditionally importing. */
  useEffect(() => {
    if (exam_info) {
      import(exam_info)
      .then((dataFromDb) => {
         setData(dataFromDb.default);
      });
    }
  }, [])

Made sure that exam_info has the valid import path and is in STRING format. Error: Invalid call at import statement.

When tried with explicit typed string within the same file, it works.

/* Taking some information from previous screen. */
  const{
    exam_info
  } = route.params;

  /* State to store the data. */
  const[data,setData]=useState([]);

  /* Conditionally importing database. */
  useEffect(() => {
    if (exam_info) {
      const typedPathName = '../../database/previous_year/previous23';
      import(typedPathName)
      .then((dataFromDb) => {
         setData(dataFromDb.default);
      });
    }
  }, [])

The above code works, but need to import data depending on what user selects in previous screen. Thanks in advance for any solution you can provide.

7
  • Is exam_info === "'../../database/previous_year/previous23'" true? To make sure we compare the same things. Also, typedPathName and pathName are the same thing, not sure what you're trying to achieve there. Commented Mar 17, 2024 at 7:00
  • @mikabytes , exam_info === "'../../database/previous_year/previous23'" is TRUE. Basically the problem is, when the path name comes from previous screen, and is used while importing, it throws an error. But when the path name is manually set in the same screen, it works as expected. Commented Mar 17, 2024 at 13:00
  • Okay. Then I'm at a loss. It should work. import does not differentiate where the string comes from. Consider if there may be any assumption, any other way, that your code might fail. Also, just to get you moving, you could try using fetch instead of import and then run eval on it. Maybe that'll give you some more information about what's going on. Commented Mar 17, 2024 at 13:45
  • 1
    @mikabytes "import does not differentiate where the string comes from." - but maybe the bundler or other react-native build tool does Commented Mar 17, 2024 at 14:11
  • @Bergi Indeed. If a bundler is used, it's worth looking at the compiled code. We might have made some assumptions about that too. Commented Mar 17, 2024 at 14:17

0

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.