1

I need to load my data file from https://s3.eu-central-1.amazonaws.com/easy-client-assets/HomeView.json and use it in my component.

something like:

import Data from 'https://s3.eu-central-1.amazonaws.com/easy-client-assets/HomeView.json'

any idea how I can do it?

2

3 Answers 3

0

You can use a loader and configure it to be used in webpack. With webpack >= 2.0.0 you do not need a loader. Webpack will automatically handle the import. Here is the link to a loader module.

Sign up to request clarification or add additional context in comments.

Comments

0

Please try this for your understanding.

xyz.json

// single data [{age:21}]

// multiple data [{age:24},{age:35},{age:25}]

import data from '../components/xyz.json';

Const parsedJson = JSON.parse(data);
// accessing single data
Console.log(parsedJson.age);

// accessing multiple data in JSON
Console.log(parsedJson[0].age);
Console.log(parsedJson[1].age);

// convert Json to string
Console.log(JSON.stringify(parsedJson));

I hope it will give you some idea.

Comments

0

With out some sort of a web pack plugin you cannot reference S3 files with an import statement. import is for local files only.

I recently solved a similar situation where I wanted to use s3 to host a configuration file.

I solved it with a useEffect hook and fetch to load the file from a url. For local development I use serve to host a local version and the exact url being a .env config value (and using dot-env to handle different build environments).

(note, I use almost exclusively functional react components. you could translate this to a class component and use componentDidMount)

  const [data, setData] = useState([]);

  useEffect(()=>{
    fetch(process.env.REACT_APP_CONFIG_URL)
  .then(response => response.json())
  .then((jsonData) => {
    // jsonData is parsed json object received from url
    setData(jsonData)
  })
  .catch((error) => {
    // handle your errors here
    console.error(error)
  })
  },[]) //empty array to get `componentDidMount` only and not have the `useEffect` fire on `componentDidUpdate`

This gets the data into the react state and using cache headers limits how often a user grabs the config file.

As for the webpack plugin, this exists but I have never used it https://github.com/egoist/import-http

Comments

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.