Akash Das
Akash Das

Reputation: 9

Dynamically evaluated named import in react/javascript

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.

Upvotes: 0

Views: 38

Answers (0)

Related Questions