My name is Jose and i'm trying to fetch data Json in an array to be displayed with react. My json file is:
[{"nid":"460","title":"Prueba local","parent":"null"},
{"nid":"458","title":"Otra prueba","parent":"null"}...
My js file is:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios'
import './index.css';
class Ramas extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount(){
axios
.get('../proceso.json')
.then(({ data })=> {
this.setState({
data
});
})
.catch((err)=> {console.log('no recibido')})
}
I do not get any results. I appreciate any help.
My folder structure:
react_root
-nodemodules
-public
--index.html
-src
--index.js
The json file is in vps.../fuentes/proceso.json. It's another server an i can access to it via url
Thank you
There is no need of axios for this,
The real use of axios is when you want to fetch data from API or out of your server , if proceso.js was on a different server then its good to use.
What you can do is create one file ;
// proceso.js
export default [
{"nid":"460","title":"Prueba local","parent":"null"},
{"nid":"458","title":"Otra prueba","parent":"null"}
...
]
Then use it like :
import proceso from 'path/to/proceso.js';
componentDidMount(){
this.setState({
data : proceso
});
}
If your json file is being updated by server then put the file inside public folder and then try to call axios via public folder path,
Because once the build is generated, you will not be able to access other directories, like src directory
Related
I have started with vue and D3. I just want to show my csv data in the console but when I try to do it with D3 CSV function is not working at all. Appears an array of 16 HTML elements which are in index.html, would you mind helping me with this?
This is my project structure:
This is my component code:
<template>
</template>
<script>
import * as d3 from "d3";
import { csv } from 'd3';
export default {
name: 'mycomponent',
data() {
return{
dataset: [],
}
},
async mounted(){
const data = await d3.csv('./datasets/dataset.csv')
this.$data.$dataset = Object.freeze(data)
console.log(data);
}
}
</script>
This is home:
<template>
<mycomponent></mycomponent>
</template>
<script>
import mycomponent from '#/components/mycomponent.vue'
export default {
name: 'Home',
components: {
mycomponent,
},
}
</script>
And this is what I get in console:
The d3.csv function will execute at runtime not compile-time so you have to put your csv file in public directory then use it as usual public files.
let data = await d3.csv("/datasets/dataset.csv")
Or if you want to load your csv file at compile-time you can import it as string and use d3.csvParse instead.
import dataset from '#/datasets/dataset.csv'
let data = d3.csvParse(dataset);
I would prefer the first method, in the second method your csv file might cause your script file too big.
Example
using the nextjs framework the redux-persist is not creating the local storage values. After login the persist:root is not showing in the local
In the reactjs framework, I have tried the redux persist the persist:root created in the local storage but in the nextjs framework the same method I am following the errors not coming but the persist:root is not showing
in the local storage
//store.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
import { persistReducer } from 'redux-persist';
import nextConnectRedux from 'next-connect-redux';
import storage from 'redux-persist/lib/storage/session';
const persistConfig = {
key: "root",
storage: storage,
}
const persistedReducer = persistReducer(persistConfig, reducers)
const middleware = [thunk];
const composeEnhancers =
typeof window !== 'undefined' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
}) : compose;
const enhancer = composeEnhancers(
applyMiddleware(...middleware),
);
const store = () => {
return createStore(
persistedReducer,
{},
enhancer
)};
const nextConnect = nextConnectRedux(store)
export default nextConnect;
// index.js
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';
import nextConnect from '../store';
import Route from '../routes';
import { BrowserRouter } from "react-router-dom";
class App extends Component {
render () {
const persistor = persistStore(nextConnect);
return (
<Provider store={nextConnect}>
<PersistGate loading={null} persistor={persistor}>
<BrowserRouter>
<Route/>
</BrowserRouter>
</PersistGate>
</Provider>
)
}
}
export default App;
I want the persist:root in the local storage to be showed
if you are rendering React on the server, you cant use redux-persist with default configs
When you are using redux-persist with the default configuration, means you are storing your data on browser storage and you don’t have a browser on the server
The following implementation shows you how to integrate Redux Persist into Next.js
rootReducer.js
store.js
_app.js
That's it
resource
Redux Persist with Next.js
I have a structure of src/resource/file.json.
1.By installing load-json and using require:
class App extends Component{
constructor(props) {
super(props);
this.state = {summaryData: [], sortBy: null};
this.sortContent = this.sortContent.bind(this);
}
componentWillMount() {
require('../resource/file.json')
.then(response => {
// Convert to JSON
return response;
})
.then(findresponse => {
// findresponse is an object
console.log(findresponse);
this.setState({summaryData: findresponse});
})
.catch(norespone => {
console.log('Im sorry but i could not fetch anything');
});
}
And appears the message :
Module not found: Can't resolve '../resource/file.json' in 'C:\Xampp\htdocs\path\to\app\src\pages'
Through myJSON:
request('https://api.myjson.com/bins/{id..}').then(sumres => {
if (sumres) {
this.setState({summaryData: sumres});
console.log(this.state.summaryData);
}
});
}
But nothing appears in the console or the network tab. Cans someone propose a solution?
Is it possible to load the json file without installing a local server?
Yes! It is possible to load JSON into your page. At the top of script where you import your modules, import your json file.
Example:
import React from 'react';
import jsonData from '../resource/file.json';
etc...
And in your case, if you're trying to set it to state, just set the state when the component initializes.
constructor(props) {
super(props);
this.state = {
summaryData: jsonData.myArray,
sortBy: null
};
this.sortContent = this.sortContent.bind(this);
}
Hope this helps!
I have a file for configuring my OpenID Connect authentication
export const authMgr = new Oidc.UserManager({
userStore: new Oidc.WebStorageStateStore(),
authority: **appsetting.oidc**
})
I want to access my state in order to get the value of appsetting.
I did this:
import store from './store'
const appsetting = () => store.getters.appsetting
but my appsetting is always returning undefined
what I my missing?
Store:
app.js
const state = {
appsetting: appsetting,
}
export {
state
}
getters.js
const appsetting = state => state.appsetting
export {
appsetting
}
index.js
export default new Vuex.Store({
actions,
getters,
modules: {
app
},
strict: debug,
plugins: [createLogger]
})
when I print the value of store.getters, it returns this:
{
return __WEBPACK_IMPORTED_MODULE_2__store__["a" /* default */].getters;
}
No the actual store objects
Try to import 'store' with curly brackets
import {store} from '../store/index'
store.getters.appSettings
Another option is to access from the vue property
import Vue from 'vue'
Vue.store.getters.appSettings
As for 2023 accesing store with
import {store} from '../store/index'
store.getters.appSettings
wasnt working for me but after removing curly brackets like so:
import store from '../store/index'
store.getters.appSettings
It started working as intended
I want to load Constant File in Angular 2(which is a Normal TypeScript File) having WebAPI EndPoints.
In Angular1.x. we used to have constants for the same.
How in Angular 2 I can Implement the Same?
I have created the .ts file.My main concern lies in how to load the file beforehand every Other class File loads.
.ts file :
export class testAPI {
getAPI = "myUrl";
}
In service file I am using the same by doing Normal Import:
constructor(private http: Http) {
//console.log(this.test);
console.log(this.testing.getAPI);
//this.test.load();
}
I am getting the Console as Undefined.(Must be because my Service class is loading before API Class).
Thanks in Advance.
UPDATES
Inspired with the solution for this particular problem created ngx-envconfig package and published it on NPM registery. It has the same functionalities as it is provided in this answer and even more.
You can have the JSON file somewhere in assets folder like: assets/config. Depending on whether the environment is dev or not you can use two .json files, one for development and one for production. So you can have development.json and production.json files, where each one will keep the appropriate API endpoints.
Basically you need to go through the following steps:
1. Setting up environment (skip this step if you have it already)
Create two files in src/environments folder:
environment.prod.ts
export const environment = {
production: true
};
environment.ts
export const environment = {
production: false
};
2. Create JSON config files
assets/config/production.json
{
"debugging": false,
"API_ENDPOINTS": {
"USER": "api/v1/user",
...
}
}
assets/config/development.json
{
"debugging": true,
"API_ENDPOINTS": {
"USER": "api/v1/user",
...
}
}
3. Create a service as follows
Note depending on the environment, the ConfigService will load the appropriate file
import { Injectable, APP_INITIALIZER } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs';
import { environment } from 'environments/environment'; //path to your environment files
#Injectable()
export class ConfigService {
private _config: Object
private _env: string;
constructor(private _http: Http) { }
load() {
return new Promise((resolve, reject) => {
this._env = 'development';
if (environment.production)
this._env = 'production';
console.log(this._env)
this._http.get('./assets/config/' + this._env + '.json')
.map(res => res.json())
.subscribe((data) => {
this._config = data;
resolve(true);
},
(error: any) => {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
});
});
}
// Is app in the development mode?
isDevmode() {
return this._env === 'development';
}
// Gets API route based on the provided key
getApi(key: string): string {
return this._config["API_ENDPOINTS"][key];
}
// Gets a value of specified property in the configuration file
get(key: any) {
return this._config[key];
}
}
export function ConfigFactory(config: ConfigService) {
return () => config.load();
}
export function init() {
return {
provide: APP_INITIALIZER,
useFactory: ConfigFactory,
deps: [ConfigService],
multi: true
}
}
const ConfigModule = {
init: init
}
export { ConfigModule };
4. Integrate with app.module.ts
import { NgModule } from '#angular/core';
import { ConfigModule, ConfigService } from './config/config.service';
#NgModule({
imports: [
...
],
providers: [
...
ConfigService,
ConfigModule.init(),
...
]
})
export class AppModule { }
Now you can use ConfigService wherever you want get the necessary API endpoints defined in config .json files.
In Angular 4+ projects generated with the Angular CLI, you will have the environment folder out-of-the-box. Inside of it, you will find the environment.ts files from Karlen's answer. That is a working solution for configuration with one caveat: Your environment variables are captured at build time.
Why does that matter?
When you're setting up a CI/CD pipeline for your Angular app, you will generally have a build tool that builds your project (like Jenkins) and a deployment tool (like Octopus) that will grab that package (the dist folder) and deploy to the selected environment, replacing your environment variables with the correct values in the process. If you use the environment.ts files, your environment variables cannot be replaced this way because the environment.ts files do not get included in the dist folder. There is no file your deployment tool can pick up and edit.
What can we do? we can add a JSON configuration file inside of the assets folder. Those files are included by default in the dist folder we will want to deploy. When we want to use an environment variable, we simply import the settings like import config from '[relative/path/to/your/config/file.json]'.
When we do this, we will get something like the following error:
Cannot find module '../../config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
This is because the typescript compiler tries to import an exported module and cannot find one. We can fix this by adding the following JSON properties/values in our tsconfig.json file.
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
resolveJsonModule allows the typescript compiler to import, extract types from, and generate .json files.
allowSyntheticDefaultImports allows default imports from modules with no default export.
With this in place, we can run our project and we will find that our error is gone and we can use our config values without any issues.
Now, because this config file is included in the dist folder that gets deployed on the server, we can configure our deployment tool to replace the variable values with the values specific to the environment to which we want to deploy. With this in place we can build our Angular app once and deploy it anywhere.
Another added benefit is that most deployment tools like Octopus ship with native JSON support so you can configure it to replace environment variables in your JSON file quite easily. The alternative is using a regex solution to replace environment variables in a .ts file, which is comparatively more complicated and prone to mistakes.
It is possible to import JSON in TypeScript. You need to add typings:
typings.d.ts:
declare module "*.json" {
const value: any;
export default value;
}
And then import like this:
import config from "../config/config.json";
config.json:
{
"api_url": "http://localhost/dev"
}
I had same issue and in the end i give up from .ts and put it in .js :D like this:
configuration.js in root
var configuration = {
'apiHost': 'http://localhost:8900',
'enableInMemoryWebApi': false,
'authMode': 'standalone',
'wsUrl': 'ws://localhost:8900/ws'
};
module.exports = configuration;
in .ts file for ex. user.service.ts
let configuration = require('../configuration'); //in import section
#Injectable()
export class UserService {
...
getUser(id: number | string): Promise<User> {
console.log(configuration.apiHost) //will get propertye from .js file
return this.http.get(`${configuration.apiHost}/${id}`, this.headers).toPromise().then(this.extractData).catch(this.handleError);
}
}
Hope it helps
You can use Opague token to set constant values as providers
Try:
In your const file:
import { OpaqueToken } from '#angular/core';
export const CONFIG_TOKEN = new OpaqueToken('config');
export const CONFIG = {
apiUrl: 'myUrl'
};
In your AppModule set to make it a singleton provider for the app:
providers:[
//other providers,
{provide: CONFIG_TOKEN, useValue: CONFIG}
]
For injecting in constructor,
constructor( #Inject(CONFIG_TOKEN) private config)