Kit
Kit

Reputation: 359

How to load an external js file and use their data in reactjs?

I'm doing a react project using create-react-app and my current goal is to load an external js file (that is hosted in iis) and use their data.

I'm getting this file throught a script in index.html like:

<script type="text/javascript" src="http://localhost:5000/GetJsFile"></script>

Example of my js file:

var data = {
   vars: {
      id: ****,
      user ******,
      name: *******,
      date: *******,
   }
   //...
}

My question is: how can I use/access the data from js file inside a component of react js?

Upvotes: 1

Views: 2525

Answers (2)

Mohammad
Mohammad

Reputation: 127

In your utils.js page

you must change your code to this shape:

utils page

const data = {
   vars: {
      id: ****,
      user ******,
      name: *******,
      date: *******,
   }
   //...
}
export default data;

and after that in other component that you want to use this data write this code:

import data from '../../../../utils';

...
console.log('data', data);

Upvotes: 1

Andr&#233;s Hevia
Andr&#233;s Hevia

Reputation: 46

The problem with loading the JSON's data from the html file directly is that it will not be available for your react code to use.

Since you are loading it from an external source, you need to use something like fetch, axios or superagent to retrieve it.

You can either use async/await or promises.

async function loadJsonFromExternal() {
    const dataFromJSON = await axios.get('http://localhost:5000/GetJson');
    return dataFromJSON;
}

Say you have your component.js file with something like this:

import React, { useEffect } from 'react';
export default function CoolComponent (props) {
  let myName = 'Enigma';
  useEffect(() => {
      loadJsonFromExternal()
      .then((result) => { myName = result.name });
  }, [])
  return (
     <div>My name is: {myName}</div>
  )
}

That would be the approach to do.

Upvotes: 0

Related Questions