TypeError: this.state.data.map is not a function
Trying to access local json data.
import React, { Component } from 'react';
import './index.css'
class App extends Component {
constructor(){
super()
this.state = {
data: []
}
}
componentDidMount()
{
fetch("./employeeData.json")
.then(res => res.json())
.then(daabta => {
this.setState({data: daabta })
} )
}
render() {
return (
<table>
<tbody>{this.state.data.map((item, index) =>
<tr key = {index}>
<td>{item.userId}</td>
<td>{item.firstName}</td>
<td>{item.lastName}</td>
<td>{item.region}</td>
</tr>
)
})}</tbody>
</table>
)
}
}
export default App;
You can just import your json file directly at the top of your component like
import * as employeeData from "./employeeData.json";
but be careful your json data would be inside and object named default so when you want to access the data you should use employeeData.default
Related
I'm new to React. I have provided Postgresql API and I want to add those data in Material UI Table.
I've made some mistakes and I'm unable to figure to out.
I'm using API calls for the first time using Axios. So please guide me to solve this issue.
I'm using React.js for frontend work, Phoenix framework for backend, and PostgreSQL database.
The below component is used to handle API request using Axios
import axios from "axios"
import MedicineCard from './MedicineCard'
class Medicines extends React.Component {
constructor() {
super();
this.state = { medicines: [] };
}
componentWillMount() {
axios.get('http://localhost:4000/medicines')
.then(response => {
this.setState({ medicines: response.data.medicines });
})
.catch(error => {
console.log(error);
});
}
render() {
const posts = this.state.medicines.map((medicine, index) =>
<MedicineCard
key = { index }
medid = {medicine.medid}
medname = {medicine.medname}
/>
)
return (
<div>
{posts}
</div>
)
}
}
export default Medicines
Below Component is used for Material UI Table
import React from 'react'
import MaterialTable from 'material-table'
class MedicineCard extends React.Component{
render(){
const data=[
{medid:this.props.medid,medname:this.props.medname}
]
const column=[
{
title:'Medicine_ID',field:'medid'
},
{
title:'Medicine_Name',field:'medname'
}
]
return (
<div>
<MaterialTable title="Material Table"
data={data}
column ={column}
/>
</div>
);
}
}
export default MedicineCard
This component is used to display UI
import React from 'react'
import Medicines from './Medicines'
const Test = () => (
<div>
<Medicines />
</div>
)
export default Test
Please help me and guide me out to solve this issue
I'm attempting to make a request to this https://www.themoviedb.org/documentation/api API in a React project and then display JSON data on my site.
I'm using Axios to make the request and I have been able to make the request and get the appropriate JSON data and console.log it or view it in the React tools in Firefox. However, I am having difficulty displaying the data in a ul. Initially I had an error pertaining to having a unique key for each list item, and I have since resolved that (or so I believe).
Here's my request and how I am attempting to render the data:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from "axios";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
componentDidMount() {
axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=*apikeyhere*&language=en-US&page=1`)
.then(res => {
const posts = res.data.results.map(obj => [obj.title, obj.overview]);
this.setState({ posts });
});
}
/* render() {
return (
<div>
<h1>Movie API data</h1>
<ul>
{this.state.posts.map(post =>
<li key={post.toString()}>{post.title}</li>
)}
</ul>
</div>
);
}
}
*/
render() {
return (
<ul>
{this.state.posts.map(function(post, index){
return (
<div key={index}>
<h1>{post.title}</h1>
<p>{post.overview}</p>
</div>
)
}
)}
</ul>
);
}
}
As you can see I attempted multile approaches to rendering this. What's wrong with my code and why isn't the JSON data rendering in the ul on my site?
I think, you have an error inside success fuction ({title: obj.title, overview: obj.overview})
componentDidMount() {
axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=*apikeyhere*&language=en-US&page=1`)
.then(res => {
const posts = res.data.results.map(obj => ({title: obj.title, overview: obj.overview}));
this.setState({ posts });
});
}
I am new to react.js and I am trying to display data in JSON format in a table. So what I did is:
import React from 'react';
import axios from 'axios';
class TableUser extends React.Component {
constructor(props) {
super(props);
this.state = {
libelle_produit: ''
};
}
componentDidMount(){
axios
.get('admin/prdtId/')
.then(({ data })=> {
this.setState({
libelle_produit: data.libelle_produit
});
})
.catch((err)=> {})
}
render() {
return <div>
<p>{ this.state.libelle_produit }</p>
</div>;
}
}
export default TableUser;
i'd want to be able to access the libelle product of each component and print those on the website
[{"libelle_produit":"test produit"}]
Thanks
<div>
{ this.state.libelle_produit != '' ? this.state.libelle_produit.map( (item, index) =>
<p>{libelle_produit</p>
}
</div>
If the array isnt empty, then loop trough the array and return a p tag with the title of the libelle_produit
I am new to ReactJS,now working on small project. I am trying to load data from a JSON file,but I'm getting this "Syntax error: Unexpected token m in JSON at position 0 at JSON.parse ()". Thanks in advance.
Here is my code :
import React from 'react';
import dataa from './src/dataa.json';
class App extends React.Component {
constructor() {
super();
this.state = {
data:require('json!./dataa.json')
}
}
render() {
return (
<div>
<Header/>
<table>
<tbody>
{this.state.data.map((person, i) => <TableRow key={i} data={person} />)}
</tbody>
</table>
</div>
);
}
}
class TableRow extends React.Component {
render() {
return (
<tr>
<td>{this.props.data.id}</td>
<td>{this.props.data.name}</td>
<td>{this.props.data.age}</td>
</tr>
);
}
}
export default App;
and JSON data:
[{"id":"1","name":"Smith","age":"20"},
{"id":"2","name":"Jackson","age":"94"},
{"id":"3","name":"Doe","age":"80"},
{"id":"4","name":"Johnson","age":"37"}]
I'm trying to make a request from an external API in angular 2.
I want to manage the data request in 2 files and display the result as json.
My data-output component looks like this:
import {Component} from '#angular/core'
import {DataService} from './datavisualisation.service'
#Component({
selector: 'app-datavisualisation-output',
template: `
`
})
export class DatavisualisationOutput {
constructor(dataservice: DataService) {
dataservice.data
.subscribe(
data => this.data = data,
console.error,
() => console.log('Look at this:' + data)
);
}
}
My second file for the service looks like this:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class DataService {
constructor(http:Http) {
this.data = http.get('http;//...API')
.map(response => response.json());
}
}
...but the console shows the following error:
components/datavisualisation/dataservices/datavisualisation.output.service.ts:12:26
Property 'data' does not exist on type 'DataService'.
components/datavisualisation/dataservices/datavisualisation.output.service.ts:14:29
Property 'data' does not exist on type 'DatavisualisationOutput'.
components/datavisualisation/dataservices/datavisualisation.output.service.ts:16:43 Cannot find name 'data'.
components/datavisualisation/dataservices/datavisualisation.service.ts:8:13
Property 'data' does not exist on type 'DataService'.
What am i doing wrong here?
You should define the dataproperty on your DatavisualisationOutput component:
export class DatavisualisationOutput {
public data: any; //this one
constructor(dataservice: DataService) {
dataservice.data
.subscribe(
data => this.data = data,
console.error,
() => console.log('Look at this:' + data)
);
}
}
and on your DataService:
#Injectable()
export class DataService {
public data: any;
constructor(http:Http) {
this.data = http.get('http;//...API')
.map(response => response.json());
}
}
and on DatavisualisationOutput... Just.. always define any property you access with this.
As #PierreDuc already said you should define that variable inside component class to make it available inside Class context.
Also you should create a method inside a service which would be responsible for data. Just make an call same method from another component and it will return the data which has retrieved last time.
Code
#Injectable()
export class DataService {
data: any;
constructor(http:Http) {
}
getData(){
if(this.data) return Observable.of(this.data)
else
return http.get('http;//...API')
.flatMap(response => {
this.data = response.json();
return Observable.of(this.data)
);
}
}
Component
export class DatavisualisationOutput {
myData: any;
constructor(private dataservice: DataService) {
dataservice.data
.subscribe(
data => this.data = data,
console.error,
() => console.log('Look at this:' + data)
);
}
ngOnInit(){
dataservice.getData().subscribe(
data => myData = data
)
}
}