dynamically update require path

Related searches

I have local json files and i want to update the paths to these files dynamically in React. For instance, I have

file1.json

file2.json

inside each json file i have objects.

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
  state = {
      user: require('./'),
      userSelected: null,
    };
  handleChange =(e) => {
    var data = './json/' + e.target.value + '.json';
    try{
      this.setState({
        user: require(data), userSelected: e.target.value
        });
    }catch(err){
      console.log(err.message)
    }
  }

  render() {
    return (
      <div>
      <input value={this.state.userSelected} onChange={this.handleChange}/>
        <h1> {this.state.user.name} </h1>
        you are {this.state.user.age} years old
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

this doesnot work. i get not declared as a System.registerDynamic dependency of index.js error

I already tried nesting inside function - not working, import - returns an empty promise, konfig - not working

i need to access the json data and display it in name and age dynamically with change in state.user

the requirement is to use require function. I cannot use fetch or axios.

Edited To solve your issue System.registerDynamic dependency, you have to configure webpack to load json files

webpack.config.js

module.exports = {
  module: {
    loaders: [
      {
        test: /\.json$/,
        loader: 'json-loader'
      }
    ]
  }
}

And then the file can be load by

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
  state = {
      user: require('./'),
      userSelected: null,
    };
  handleChange =(e) => {
const value = e.target.value;
  var data = require('json!./${value}.json'); // forward slashes will depend on the file location

    try{
      this.setState({
        user: data, userSelected: e.target.value
        });
    }catch(err){
      console.log(err.message)
    }
  }

  render() {
    return (
      <div>
      <input value={this.state.userSelected} onChange={this.handleChange}/>
        <h1> {this.state.user.name} </h1>
        you are {this.state.user.age} years old
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

How to use `import/require` with dynamic path? - help, I would like to use import/require with dynamic path, for example const path = '../ imports/modules/core/startup/client'; import path; In the recent blog entitled The benefits of Windows 10 Dynamic Update, Monika Sinha provided an overview of Dynamic Update, the benefits of enabling it, how it works, and how to manage this content in a managed environment. For IT pros that want to have these updates applied to their Windows 10 imag

You can make use of axios to fetch data from the json file.

axios.get('../public/users.json') // JSON File Path
   .then( response => {
     this.setState({
     data: response.data
   });
 })
 .catch(function (error) {
   console.log(error);
 });

Require file dynamically by variable � Issue #6391 � facebook/react , I appreciate your help, but I'd like to know if there is any way to require file with dynamic string path or require all files in dir without knowing what are they. Further, Dynamic Update also eliminates the need to install a separate quality update as part of the in-place upgrade process. From an IT perspective, using Dynamic Update reduces the need to apply separate updates to recently installed systems and makes it easier to get your devices up to date with the latest available quality update in one step.

U are jest getting json data from your local file then use fetch api for that

handleChange =(e) => {
    var data = './json/' + e.target.value + '.json';
    fetch(data)
  .then((response) => {
    return response.json();
  })
  .then((response) => {
    this.setState({
        user: response, userSelected: e.target.value
        });
  });
  }

Dynamic imports, The module path must be a primitive string, can't be a function call. This won't But how can we import a module dynamically, on-demand? Do you want to request a feature or report a bug? Bug What is the current behavior? I want to dynamically require a module, how node will do it, at runtime. Use cases: require a project configuration (cwd + "projectConfig.js") require th

You could just import the file using async await.

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    user: {},
    userSelected: null
  };
  handleChange = async ({ target }) => {
    const value = target.value;
    var json = `./${value}.json`;
    try {
      const data = await import(json);
      this.setState({
        user: data,
        userSelected: value
      });
    } catch (err) {
      console.log(err.message);
    }
  };

  render() {
    return (
      <div>
        <input value={this.state.userSelected} onChange={this.handleChange} />
        <h1> {this.state.user.name} </h1>
        you are {this.state.user.age} years old
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

import, This is often a relative or absolute path name to the .js file containing the module. Certain bundlers may permit or require the use of the extension; check your environment. Only single When importing a default export with dynamic imports , it works a bit differently. Update compatibility data on GitHub� A couple of things - It is possible to make some dynamic decisions at runtime but not all. The packager still needs to know the set of files that you potentially could import at runtime in order to include them in the bundle.

https://codesandbox.io/s/7om3w3r4p0 worked for me. Could dynamically import the files using require module

Webpack and Dynamic Imports: Doing it Right, Update: If you're using Babel 7.5+ it already includes the dynamic import plugin In Webpack normally we load images as modules using the file loader. The file loader will basically map the emitted file path inside a module. Once the update map is created, it is applied to the desired persisted workflow instances. Once the dynamic update is applied, the workflow instance may be resumed using the new updated workflow definition. There are four steps required to create and apply an update map. Prepare the workflow definition for dynamic update

The GetData.asp page returns XML in the correct format for InfoPath to open it as a form file. To do this, click Start, click Run, type the path of the GetData.asp page, and then click OK. The path that you type resembles the following:

This means dynamic requires are supported but will cause all matching modules to be included in the bundle. require.context. You can create your own context with the require.context() function. It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files

The './' relative ID can only be resolved correctly if the module asks for a module-specific require function (a "local require"). Since the FutureViewPromise module uses require([]) dynamically, I would remove the UMD boilerplate, since it will only work with an AMD loader, and just do:

Comments
  • instead of using require path, U can use ajax request, its will helpful for you
  • Tried. Doesn't work. Same error "not declared as a System.registerDynamic dependency of index.js"
  • @Andruraj have you configure webpack?
  • you should have webpack.config.js file where you should the the configuration to load json files, and install the loader see on --> github.com/webpack-contrib/json-loader
  • the requirement is to use require function. I cannot use fetch or axios
  • the requirement is to use require function. I cannot use fetch or axios.
  • Tried. Doesn't work. Same error "not declared as a System.registerDynamic dependency of index.js"
  • There is some issue with configuration because it is working for me. codesandbox link. That is the reason we should bootstrap with create-react-app to avoid configuration issue. Try CRA.
  • Its because it goes into catch block and state is not updated, check again, I have updated the code
  • ya i noticed that, I'm a beginner, so I dont know where to find and edit what in webpack, because its working in sandbox, but not on my pc localhost. Thanks anyway :)
  • the requirement is to use require function. I cannot use fetch or axios.