React - load all data from json into component - javascript

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';

Related

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;

Can't add json in reactjs [duplicate]

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.

ReactJS + D3: Parse local CSV file and passing it to state with d3-request

This might be a really simple thing to do and there are multiple Q&A regarding this, but i can't find a solution to my problem..
I'm trying to parse an entire CSV file with d3-request module and set the state with this data in a React component. From my understanding the d3-request module parses each row of the CSV file one by one, so I can't simply do this:
import {csv} from 'd3-request';
componentWillMount() {
csv('./data/test.csv', (error, data) => {
if (error) {
this.setState({loadError: true});
}
this.setState({
data: data
});
})
}
So i thought of doing this instead. The "..." or spread syntax helps to copy each array.
componentWillMount() {
csv('./data/elements-by-episode.csv', (error, data) => {
if (error) {
this.setState({loadError: true});
}
this.setState({
data: data.map(d => ({...d}))
});
})
}
render() {
console.log(this.state.data);
}
But the console.log prints out the html contents of the page itself.
test.csv
'title', 'A', 'B'
'E01', 1, 0
'E02', 5, 0
'E03', 10, 2
Hoping to transform CSV to this, after parsing:
this.state.date = [
['title', 'A', 'B'],
['E01', 1, 0],
['E02', 5, 0],
['E03', 10, 2]
];
EDIT:
Seems that the problem in the first place is reading in the CSV file using d3-request in React app.
componentWillMount() {
csv('test.csv', (error, data) =>
console.log(data);
});
}
Console log prints out the HTML structure of the page....
I was facing the same error some time ago and a way to solve it is as follows.
import React, { Component } from 'react';
import * as d3 from 'd3';
import data from './data.csv';
d3.csv(data, function(data) { console.log(data); });
You need to import your dataset first using React's method "Import" and then parse it using D3.csv function.
Hope it works for you! All the best.
Edit: I am using D3.js 5.5.0 and React.js 16.4.1 and using Yarn to start the application.
import React, {Component} from 'react';
import './App.css';
import * as d3 from 'd3';
import data from './data_set/data.csv';
class App extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
d3.csv(data).then(function(data) {
console.log(data)
}).catch(function(err) {
throw err;
})
}
render() {
return (
<div className = "App" >
<div> Data Visualization </div>
</div>
);
}
}
export default App;
Making use of promises will do the job ;).
If you are using Create React App, there are some special instructions for using files inside the public directory.
https://create-react-app.dev/docs/using-the-public-folder/
As Feras mentioned in their comment, importing will bundle the data along with your application code, which might not be what you want.
From within React code, you need to prepend process.env.PUBLIC_URL to the file path in the public directory. So in your case,
componentWillMount() {
csv(process.env.PUBLIC_URL+'/test.csv', (error, data) =>
console.log(data);
});
}

React Native this.state.questions.map() is not a function

It's my understanding that the most common use care for iterating over a list of data is map, which is an array method that iterates over an array, but when I tried to apply it here:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
class QuestionList extends Component {
state = { questions: [] };
componentWillMount() {
axios
.get('https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean')
.then(response => this.setState({ questions: response.data }));
}
// renderQuestions() {
// return this.state.questions.map(question => <Text>{}</Text>);
// }
render() {
console.log(this.state);
return (
<View>
<Text>{}</Text>
</View>
);
}
}
export default QuestionList;
I ended up getting an error in the Simulator saying that this.state.questions.map() is not a function. I have searched for similar errors online, but they do not apply to my use case.
Keep in mind I commented out the code and erased what I had inside of <Text> because my machine was about to take off.
I don't know what this error means short of not being able to use the map() array helper method, does that mean I need to be applying a different helper method to iterate through this list of questions?
I did a console log of the response object like so:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
class QuestionList extends Component {
state = { questions: [] };
componentWillMount() {
axios
.get('https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean')
.then(response => console.log(response));
}
render() {
console.log(this.state);
return (
<View>
<Text>{}</Text>
</View>
);
}
}
export default QuestionList;
and I got back the response object in the console:
from axios with a status of 200 which means the request was successful. You will notice I also go the data property and inside that is the results property and then the category with questions is inside of it:
So I am wondering if its that results property that I need to also implmement, but when I tried it I would get map() undefined.
Your API returns an object, which has no map method.
response.data.results is an array so change it to that if you intend to map over it:
this.setState({ questions: response.data.results }))
It's advisable to use componentDidMount instead of componentWillMount for async update.

how to display data in table using json in react js?

i have JSON like this
i want to use this JSON and display data in Table using react js.
this is how i display data from JSON file.
import React, { Component } from 'react';
import data from './data.json';
class App extends Component {
render() {
return (
<ul>
{
data.map(function(movie){
return <li>{movie.id} - {movie.title}</li>;
})
}
</ul>
);
}
}
export default App;
how to load JSON from URL and display it in table using reactjs?
You could fetch the JSON once the component will mount, and when you eventually resolve it you can update the state of the component:
import React, { Component } from 'react';
class App extends Component {
// initially data is empty in state
state = { data: [] };
componentDidMount() {
// when component mounted, start a GET request
// to specified URL
fetch(URL_TO_FETCH)
// when we get a response map the body to json
.then(response => response.json())
// and update the state data to said json
.then(data => this.setState({ data }));
}
render() {
return (
<ul>
{
this.state.data.map(function(movie){
return <li key={movie.id}>{movie.id} - {movie.title}</li>;
})
}
</ul>
);
}
}
export default App;
If you're unable to use fetch, you could use some other libraries like superagent or axios. Or you could even fall back to good ol' XMLHttpRequest.
On another note, when building a list of component it is important they each child have a unique key attribute. I also updated that in the code, with the assumption that movie.id is
Example axios code:
axios.get(URL)
.then(response => response.data)
.then(data => this.setState({ data }));
EDIT: as trixn wrote in a reply, componentDidMount is the preferred place to fetch data. Updated code.
EDIT 2: Added axios code.
You can use axios to send http requests.
It looks like this :
const response = await axios.get(your_url_here);
const items = response.data.items;
About await keyword : How to use await key word on react native?
This is axios GitHub page for the docs : https://github.com/axios/axios
Hope it helps.
You can use the fixed Data table to display the data from the json Response.Since the data is vast and it would be difficult to manage the conventional table, this would be a better alternative.
The documentation is given at
https://github.com/schrodinger/fixed-data-table-2/blob/master/examples/ObjectDataExample.js
This link will help you.

Categories