Can't add json in reactjs [duplicate] - javascript

This question already has an answer here:
import a Json file in a React Component
(1 answer)
Closed 4 years ago.
I'm beginner in reactjs and I'm trying import JSON file in my js. When I execute the.js with JSON (like in example but replace what is in the comment by the four first var) everything works but when I'm try to import from another file I have this Error. "TypeError: fs.readFileSync is not a function".
First
import React, { Component } from 'react';
import './App.css';
//import people from './db/dab.json';
var fs = require('fs');
var filname = '/db/dab.json';
var data = fs.readFileSync(filname, 'utf-8');
var people = JSON.parse(data);
console.log(people);
/*var people = [
{
"id": "johnson",
"first_name": "Karol",
"last_name": "Johnson",
"rank":"1",
},
{
"id": "smith",
"first_name": "John",
"last_name": "Smith",
"rank":"2",
]*/
function searchingFor(term){
return function (x) {
return x.first_name.toLowerCase().includes(term.toLowerCase()) || x.last_name.toLowerCase().includes(term.toLowerCase()) || x.birth_city.toLowerCase().includes(term.toLowerCase()) || x.address.address1.toLowerCase().includes(term.toLowerCase());
}
}
class App extends Component {
constructor(props) {
super(props);
this.state={
people: people,
term:'',
}
this.searchHandler = this.searchHandler.bind(this);
}
searchHandler(event){
this.setState({ term: event.target.value})
}
render() {
const {term, people} = this.state;
return (
<div className="App">
<form>
<input type="texte"
onChange={this.searchHandler}
value={term}
/>
</form>
{
people.filter(searchingFor(term)).map( person =>
<div key={person.id}>
<h3>{person.rank}</h3>
)
}
</div>
);
}
}
export default App;
Thank you for helping.

The client-side apps (the ones that execute in a browser) doesn't have access to your file system, so you would have to import the file directly. This can only happen if the file is already in the file system when the app execute.
With this said the way to do it is as follows.
import people from './db/dab.json';
people = JSON.parse(people);

If this is taking place in your browser, then you won’t have access to fs which is limited to server-side NodeJS. You’ll just access the JSON through web apis or window.fetch() and then just JSON.parse(data) to get access to it as a JS object.

Related

N.map is not a function

I'm brand new to react, and I'm trying to read an inline JSON object and display that data as a list of results
import SearchPage from './views/SearchPage'
function App() {
const horseDataJSON = window.horseData;
const [horses, setHorses] = useState(horseDataJSON);
console.log(horseDataJSON);
return (
<div className='app'>
{horses && <SearchPage horses={horses} />}
</div>
);
}
export default App;
However I am receiving the error TypeError: N.map is not a function. I have seen several solutions here using .map(), which leads me to think I'd do something like this
{horses &&
horses.map((horse) =>
<SearchPage horses={horses} />
))
}
But that just seems wrong given that my SearchPage component is going to be a list of horses, so using "horse" isn't going to work.
Terrible explanation of problem, but I am unfamiliar with React terminology. What is the correct way to integrate "map" into the above to resolve this error?
Example of horse.json as requested
[
{
"id": 75222685,
"name": "Mellby Glader*",
"link": "https://lardev-16953.bolt91.servebolt.com/product/wc-donation-mellby-glader/",
"total_donation_amount": 0,
"max_amount": "30000",
"dontation_ended": false
},
]
If horseDataJSON variable is a JSON format, you need to parse it with
const parsedHorseData = JSON.parse(horseDataJSON)
So you can apply array method on it.

Override the constant file values in React

constant file -> constant.js
export default {
CITY: 'Banglore',
STATE: 'Karnataka'
}
Show Default City Name -> address.jsx
import React from "react";
import CONSTANTS from "./constants";
import "./styles.css";
const Address = () => {
return (
<div className="App">
<p> City : {`${CONSTANTS.CITY}`} </p>
<p> State : {`${CONSTANTS.STATE}`} </p>
</div>
);
};
export default Address;
expected output:
city: banglore
state: karnataka
we are importing the constant values from constant.js file, now the problem is we have to make one API call which may return overriding values for the constant keys
example of API response:
{
CITY: 'Mysuru'
}
then CITY is constant file should override with the new value which come after API response and rest other keys should keep their values same.
expected output:
city: Mysuru
state: karnataka
this the basic problem case for me, actually our application already in mid phase of development and more than 500+ constant keys are imported in 100+ components.
1. we are using redux in our application
2. we have to call API only once that should effects to all the components
what is the best way to achieve this problem, how can i override my constant files once i make the call to backend, Thank you
Since the question has changed, so does my answer (keeping the original one below). I'd suggest to rebuild the constants file to either return the constants or from Localstorage. However, be aware that the current components will not be rebuild using this approach. Only thing that'll trigger a rebuild is either use Redux for this or local state management.
const data = {
CITY: 'Banglore',
STATE: 'Karnataka'
}
const getData = () => {
let localData = window.localStorage.getItem('const-data');
if (!localData) {
axios.get('url')
.then(response => {
localData = {...response.data};
window.localStorage.setItem('const-data', JSON.stringify({...localData}));
});
}
return localData ? localData : data;
}
export default getData();
Original answer:
This is how I'd solve it using local state. It was some time ago since I was using Redux. Though the same principle should apply instead of putting the data in local state, put it in the Redux.
I prefer the simplicity of using local state whenever there's no need to share data over multiple components.
import React, { useEffect } from "react";
import CONSTANTS from "./constants";
import "./styles.css";
const Address = () => {
const [constants, setConstants] = useState({...CONSTANTS});
useEffect(() => {
//api call
//setConstants({...apiData});
}, []);
return (
<div className="App">
<p> City : {`${constants.CITY}`} </p>
<p> State : {`${constants.STATE}`} </p>
</div>
);
};
export default Address;

React Tensorflow JS load the csv file uploaded by the user

I can load csv files from external URL, but when I try to load a file that the user uploaded to the web, it shows an empty Object.
The object appears to be loaded, but you can`t access the information in any way. The solutions I found online were to setup servers, but I didn't want to do that. I want to have an client-side only web app with tensorflowJS.
main.js:
export default function Main() {
const [archivo, setArchivo] = useState();
const cargarArchivo = (archivo) => {
setArchivo(archivo);
};
async function realizarCalculos() {
await preprocesamiento(archivo);
}
return (
<div>
<Dropzone cargarArchivo={cargarArchivo} />
<Button
onClick={realizarCalculos}
style={{ margin: "5vh" }}
variant="outlined"
>
Calcular Caudales
</Button>
</div>
);
}
Dropzone.js:
class Dropzone extends Component {
constructor(props) {
super(props);
this.state = {
files: [],
};
}
handleChange(files) {
this.props.cargarArchivo(files[0]);
this.setState({
files: files,
});
}
render() {
return (
<DropzoneArea
acceptedFiles={[".csv"]}
onChange={this.handleChange.bind(this)}
/>
);
}
}
export default Dropzone;
Tensorflow JS:
import * as tf from "#tensorflow/tfjs";
export async preprocesamiento(archivo){
const csvDataset = tf.data.csv(archivo.path);
}
TensorflowJS tf.data.csv works with fetch under the hood. Meaning that you can't load local files, see this question. I resolved the issue by creating an URL object with the URL class, and serving the url to tensorflow :
import * as tf from "#tensorflow/tfjs";
export async preprocesamiento(archivo){
const url = URL.createObjectURL(archivo);
const csvDataset = tf.data.csv(url);
}

Data from Gatsby GraphQL always returns undefined?

Gatsby noob here so please bear with me. I have a component that accepts props from the index.js where it is supposed to receive data from an array of objects but will always receive the error TypeError: Cannot read property 'map' of undefined where it's referring to the Hero.js component index.js is calling for.
My assumption is that the data being queried in index.js is either not specific enough or that it is rendering the component before data is received. Here is the index.js file:
import { graphql } from 'gatsby';
import { Layout, SEO, Hero } from 'components';
const IndexPage = ({ data }) => {
const dataFetch = data.contentfulTemplateIndex.heroes;
let tester = () => {
for (let count = 0; count < dataFetch.length; count++) {
return <Hero {...props} />;
}
};
console.log(dataFetch);
let props = {
impactText: dataFetch.impactText,
labels: dataFetch.labels,
primaryLabel: dataFetch.primaryLabel,
location: dataFetch.location
// supportingText: dataFetch.supportingText.json
};
return (
<Layout>
{dataFetch && tester()}
</Layout>
);
};
export const query = graphql`
query {
contentfulTemplateIndex {
heroes {
image {
fluid {
src
}
}
impactText
labels
location
primaryLabel
supportingText {
json
}
}
}
}
`;
export default IndexPage;
Here is the Hero.js component which index.js is calling:
import { Link } from 'gatsby';
import { documentToReactComponents } from '#contentful/rich-text-react-renderer';
import cx from 'classnames';
import styles from './hero.module.scss';
const Hero = (props) => {
return (
<div>
<ul>
<Link className={styles.pills}>{props.primaryLabel}</Link>
{props.labels.map((label) => {
return <Link className={styles.pills}>{label}</Link>;
})}
</ul>
<div className={styles.grid}>
<h1>{props.impactText}</h1>
</div>
</div>
);
};
export default Hero;
It's impossible for an outsider to debug your code without a minimum reproducable example.
The best way to debug GraphQL is to use the GraphiQL interface of your browser.
Run gatsby develop. If it fails because of the TypeError remove the lines of code that cause the type error (but not the code of your GraphQL query!). You need to get your development server runnning.
Open your browser, use the URL: http://localhost:8000/___graphql
Copy your graphQL query from your code and paste it into the GraphiQL query window.
Can you access your data there? If not you made a mistake writing your query or the data is not where it's supposed to be.
This way you can make sure the data exists.
It also helps to console.log(props) so you can examine the data object:
const Hero = (props) => {
console.log(props);
return (

React - load all data from json into component

I am using React and trying to load data into my component from a local json file. I am trying to print all information, including the 'name' in a name:value pair (not just the value) to make it look like a form.
I am looking for the best way to do this. Do I need to parse? Do I need to use a map function? I am new to React so please show me solution with code. I've seen other questions similar to this but they include a lot of other code that I don't think I need.
Example of my code:
test.json
{"person": {
"name": "John",
"lastname": "Doe",
"interests":
[
"hiking",
"skiing"
],
"age": 40
}}
test.js
import React, {Component} from 'react';
class Test extends Component {
render () {
return (
)
}
};
export default Test;
I need code that lets me import from json and code inside component that displays ALL fields.
If your json is stored locally, you don't have to use any library to get it. Just import it.
import React, {Component} from 'react';
import test from 'test.json';
class Test extends Component {
render () {
const elem = test.person;
return (
<ul>
{Object.keys(elem).map((v, i) => <li key={i}>{v} {test[v]}</li> )}
</ul>
)
}
};
export default Test;
The first important question to care about is how you want to get this JSON, if I understood your problem very well it's a local JSON file. So you need to run a local server inside your app to get these values.
I'd recommend the live-server, made in node.js.
After that you can use axios to fetch data and then ...
import React, {Component} from 'react';
import axios from 'axios';
constructor (props) {
this.state = {
items: [],
}
axios.get('http://localhost:8080/your/dir/test.json')
.then(res => {
this.setState({ items: res.data });
});
}
class Test extends Component {
console.log(this.state.items);
render () {
return (
)
}
};
export default Test;
I've already put a console.log before render to show your object, and after that do whatever you want!
Use JSON.parse(json)
Example:
JSON.parse(`{"person": {
"name": "John",
"lastname": "Doe",
"interests": [
"hiking",
"skiing"
],
"age": 40
}}`);
Hi the best solution to this is using Axios.
https://github.com/mzabriskie/axios
Try look at their API its very straightforward.
And yes, you might need a map function to loop the parsed data.
I have a sample code here, which I used Axios.
import axios from 'axios';
const api_key = 'asda99';
const root_url = `http://api.jsonurl&appid=${api_key}`;
export function fetchData(city) { //export default???
const url = `${root_url}&q=${city},us`;
const request = axios.get(url);
}
request is where you get your parsed data. Go ahead and play with it
Heres another example using ES5
componentDidMount: function() {
var self = this;
this.serverRequest =
axios
.get("http://localhost:8080/api/stocks")
.then(function(result) {
self.setState({
stocks: result.data
});
})
},
by using the 2nd one. you stored the stocks as a state in here. parse the state as pieces of data.
After http://localhost:3001/ you type your directory of JSON file:
Mydata.json is my JSON file name, you type your file name:
Don't forget to import axios on the top. *
componentDidMount() {
axios.get('http://localhost:3001/../static/data/Mydata.json')
.then(response => {
console.log(response.data)
this.setState({lists: response.data})
})
}
If you're loading a file over HTTP, then you can use the built-in window.fetch() function (in browsers for the last few years, see Mozilla's developer pages for compatibility support).
fetch("https://api.example.com/items")
.then(res => res.json())
The React docs explain some other ways of doing Ajax requests (i.e. requests from within an already-loaded web page).
If your JSON is in a local file, then just import it, as others have explained:
import test from 'test.json';

Categories