Parser data with format json in react - json

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

Related

How retrieve data from an API in JSON to a list in React.Js

I am trying to retrieve data from an API in React.Js but there is an small issue with the componentDidMount function.
Here is the API https://projects.cmsbox.in/app/bms/movie/public/api/upcomingMovie
I have tried this code with other API and it worked but in this case its not working. Also checked the API in Postman and everything seems to be fine.
Thanks in advance :)
import React, { Component } from 'react';
import './index.css';
import MovieCard from './moviecard'
import Homepage from './homepage';
import { render } from '#testing-library/react';
class UpcommingMovies extends Component{
constructor(props){
super(props);
this.state = {
upcmngmovie_list: [],
dataList:[],
isLoaded:false,
}
}
componentDidMount(){
fetch('https://projects.cmsbox.in/app/bms/movie/public/api/upcomingMovie')
.then(response=>response.json())
.then(data=>{
this.setState({
isLoaded:true,
dataList:data,
upcmngmovie_list:dataList,
})
});
}
render(){
var{isLoaded,upcmngmovie_list}=this.state;
function upcomngmoviecards(val){
return(
<div className="row"><MovieCard image={val.image} movie_name={val.movie_name}/></div>
);
}
if(!isLoaded){
return <div>Loading...</div>;
}
else{
return (
<>
<Homepage />
<div className="main">
<h3>Upcomming Movies</h3>
<div className="cardlist">
{upcmngmovie_list.map(upcomngmoviecards)}
</div>
</div>
</>
)
}
}
}
export default UpcommingMovies;
The api does not return an array it is returning an object. Array is in "Movie_list" property. Update your set state function to use the property.
this.setState({
isLoaded:true,
dataList:data,
upcmngmovie_list:data.Movie_list,
})

Passing props in react - fetching

I'm simply trying to pass props through components and render it in jsx but somehow that wouldn't work. I was searching for the problem but just cannot find it.
I'm trying pass props from this component:
import React from "react";
import "../styles/Products.css";
import ProductItem from "../items/ProductItem";
class Products extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch("../products.json")
.then(response => response.json())
.then(response => this.setState({ data: response.products }));
}
render() {
return (
<div className="products-container">
<ProductItem data={this.state.data[0]} />
</div>
);
}
}
export default Products;
to this component:
import React from "react";
import "../styles/ProductItem.css";
const ProductItem = props => {
console.log(props.data, "current");
return (
<div className="product-item">
<img src="" alt="" className="bike-image" />
<div className="active-product" />
<div className="view-details">Compare</div>
<h2>Bike</h2>
<h4>downhill bike</h4>
<p>3500 PLN</p>
</div>
);
};
export default ProductItem;
And the problem is when I'm looking in my react dev tools, props has passed properly, but when I'm trying to get to attributes of the object like props.data.id, I get an error:
Cannot read property 'id' of undefined
fetch needs some time to get the response and populate the this.state.data array. So you need to check if the this.state.data[0] value is really available or not. You can try this-
render() {
return (
<div className="products-container">
{this.state.data && this.state.data.length > 0 && <ProductItem data={this.state.data[0]} />}
</div>
);
}

how to fetch array of objects from json

This is the api http://skunkworks.ignitesol.com:8000/books/ ,
I am trying to fetch the array results from it using the fetch method but instead get an error cannot fetch value of undefined
import React, { Component } from 'react';
class App extends Component {
constructor() {
super()
this.state = {
books: []
}
}
componentDidMount() {
fetch('http://skunkworks.ignitesol.com:8000/books/')
.then(res => res.json())
.then(data => this.setState({ books: data }))
.catch(e => {
console.log(e);
return e;
});
}
render() {
let book = []
book = this.state.books.results;
console.log(book[0])
return (
<div>
<h1>Books</h1>
</div>
)
}
}
export default App;
this is my code.
Also I have observed that json data are usually like [{}] but here it is {} format.
please suggest me some solution.....
As I see from your url link, you json array of data is present in the results key of the returned object from the API.
So if you're only interested by the results you should do something like that :
import React, { Component } from 'react';
class App extends Component {
state = {
books: []
}
async componentDidMount() {
const objectFromUrl = await fetch('http://skunkworks.ignitesol.com:8000/books/')
const data = await objectFromUrl.json() //first way
// or you can use destructuring way
const { results } = await objectFromUrl.json() //second way
this.setState({
books: data.results // results key contains your '[{}]' data an array of objects
})
}
render() {
const { books } = this.state
return (
<div>
<h1>Books</h1>
{books.map(book => (
<h2> {book.id} </h2>
)}
</div>
);
}
// You can use destructuring again to get only key you're interested by
render() {
const { books } = this.state
return (
<div>
<h1>Books</h1>
{books.map(({id, formats}) => (
<h2> {id} </h2>
<h2> { formats[ˋapplication/pdf’] } </h2>
)}
</div>
);
}
}

fetching json data from local file

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

Understanding React.JS JSON feed and how to parse

I've got the following code which is looping through an JSON file from an API and loops through some posts.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
//https://alligator.io/react/axios-react/
import axios from 'axios';
export default class PostList extends React.Component {
state = {
posts: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const posts = res.data;
this.setState({ posts });
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
Pulls in post slugs from Domain
</p>
<ul>
{ this.state.posts.map(post => <li>{post.name} - {post.username} </li>)}
</ul>
</div>
)
}
}
This works fine, and gets the information which was needed.
Now, in my test JSON file, the format is as follows:
https://jsonplaceholder.typicode.com/users
But in my actual JSON file from WordPress Rest API, we have another item, named core_layout:
JSON image
My issue is, trying to use the same code such as {post.name}does not get the information needed such as core_layout->image->name.
Is there an easy way around this?
Thanks all!
EDIT:
Tried the answers below, but still no luck, get the error TypeError: Cannot read property 'map' of undefined:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
//https://alligator.io/react/axios-react/
import axios from 'axios';
export default class PostList extends React.Component {
state = {
posts: [],
coreLayout: {}
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
// const posts = res.data;
//this.setState({ posts });
const { posts, core_layout: coreLayout } = res.data;
this.setState({ posts, coreLayout });
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
Pulls in post slugs from domain
</p>
<ul>
{ this.state.posts.map(post => <li>{post.name} - {post.core_layout.image.name}</li>)}
</ul>
</div>
)
}
}
EDIT 2:
Tried the below: This gets the title, but again, not the actual corelayout I need.
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
movies: []
}
}
componentDidMount() {
let dataURL = "http://zinsseruk.com/wp-json/wp/v2/posts?per_page=1";
fetch(dataURL)
.then(res => res.json())
.then(res => {
this.setState({
movies: res
})
})
}
render() {
let movies = this.state.movies.map((movie, index) => {
return <div key={index}>
<p><strong>Title:</strong> {movie.title.rendered}</p>
<p><strong>Title:</strong> {movie.core_layout.acf_fc_layout}</p>
</div>
});
return (
<div>
<h2>Star Wars Movies</h2>
{movies}
</div>
)
}
}
export default App;
Replace const posts = res.data; with const posts = res.data.core_layout;. Then you'll get an array similar to what you have in your test file.
I think you need to understand the JSON structure you receive from the API. Where is located core_layout property? Inside each post property as a children?
So in the posts loop you can use post.core_layout.image.name for image name, for example (and so on with other properties).
If core_property is at the root of the data you receive, you can load it inside your state like so:
state = {
posts: [],
coreLayout: {}
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
// This is equivalent of doing
// const posts = res.data.posts
// const coreLayout = res.data.core_layout
const { posts, core_layout: coreLayout } = res.data;
this.setState({ posts, coreLayout });
})
}
Then use it in your code by using local component state:
render() {
...
// For example image name:
console.log('image name', this.state.coreLayout.image.name)
...
}