Fetch data from JSON local file in React - json

I would need some help to fetch some data in a local file calling data.json to my React component. The data is very simple, but when i tried to connect with my component, all I have in the component appear less than the information I added from the data file.
this is my data.json:
{ "data": [
{ "id": "1",
"name": "john"
},
]}
...and this is my component where i need to fetch the data and where everything is working less than the information I want to connect and appear completely blank.
This is the function where i past the information in the first instant to send the information to the state.
function RenderFoo({data, name}) {
return (
<div>{data.name}</div>
)}
export default class Example extends Component {
constructor(props) {
super(props);
this.state = {
data : [data]
}}
render() {
const dataExample = this.state.data.map((element) => {
return (
<div key={element.url}>
<RenderFoo data ={ element }/>
</div>
)})
return (
<div>
<Card >
{dataExample}
</Card>
</div>)
The screen appear blank in the part of the component that I connect the data but without any error in the other part of the component where everything is working. I think the sintaxis to get the information is not right any reason don't read the data.
And if I change data.name in the function is giving error. I don't know if I'm missing the key or so.
Moving all the data to the main component is worthy neither because I will need to increase the data after and I will thousands of lines, and create a complete back end would be pointless for this kind of application
Thanks

Your state has a property data which is an array. Each element of that array is an object with properties id and name -- and maybe url?
So then what are the props supposed to be here:
function RenderFoo({data, name}) {
return (
<div>{data.name}</div>
)}
Does RenderFoo take a single property data which is the the whole data object? Or does it take the properties of data as individual props? Either is fine, but it feels like you are mixing the two. So remove name from the props.
<div key={element.url}>
Do all elements in your data have a url property? I'm only asking because your sample just shows name and id.
this.state = {
data : [data]
}}
This also looks suspect to me. You are taking the variable data and making it a single element in an array. I'm not sure exactly what your data variable looks like, but I think you probably want to set it as the entire state, this.state = data.
Try this:
import React, { Component } from "react";
import json from "./data";
function RenderFoo({ data }) {
return <div>{data.name}</div>;
}
export default class Example extends Component {
constructor(props) {
super(props);
this.state = {
data: json.data
};
}
render() {
return (
<div>
{this.state.data.map((element) => (
<div key={element.id}>
<RenderFoo data={element} />
</div>
))}
</div>
);
}
}
I removed the <Card> component because I don't know where you imported it from, but you can easily add it back it.

Related

How to use fetch() in react front-end to get data from express back-end?

I'm trying to make a full-stack web-app using react and express. It's going pretty well atm but here's my problem:
So I have express running in back-end. All paths are used by react router except for '/api'. At the '/api/blogposts' path my server.js send the results of a query I made to the mySQL server. (I've checked it and this part works. If I browse to /api/blogposts my browser shows a json with the contents of my blogposts table).
My problem is with getting it to show in my react front-end. I'm trying to use fetch() but it doesn't work. Here's my code for the component that is supposed to fetch the blogposts:
import React from 'react';
import './Blogposts.css';
import SingleBpost from '../SingleBpost/SingleBpost.js';
class Blogposts extends React.Component {
constructor(props) {
super(props);
this.state = {
receivedPosts: []
};
}
async getBpostsFromServer() {
const response = await fetch("/api/blogposts");
let myPosts = await response.json();
this.setState({receivedPosts: myPosts});
}
componentDidMount() {
this.getBpostsFromServer();
}
render() {
console.log(this.state.receivedPosts);
return(
<div id="Blogposts">
<SingleBpost title="OwO" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
</div>
);
}
}
export default Blogposts;
Just to clarify the {this.state.generateBlogpost()} in the render method is just to check if I can get the data for now. Once this works I will feed it into another component's props like this:
<SingleBpost title={this.state.generateBlogpost().title} date={this.state.generateBlogpost().date} author={this.state.generateBlogpost().author} body={this.state.generateBlogpost().body} />
Anyways: does anyone know why this doesn't work? I've tried a few things but I just can't get it to work. What am I doing wrong?
Thanks in advance for any help!
You need to set the state of the variable receivedPosts in the fetch function like this :
this.setState({receivedPosts: results});
Also, you can call the function generateBlogpost() at the load of the Component Blogposts by adding the following function :
componentDidMount() {
this.generateBlogpost();
}
this one is useless
.then((results) => {
this.state.receivedPosts = results;
});
return this.state.receivedPosts;
}
//instead you should use setState({receivedPosts: data.data})

How to define a state with JSON data (using react and axios)

I am a little confused about how to go about this. So I have this JSON file called posts.json.
[
{
"id": 1,
"title": "Kylie Jenner",
"content": "Social Media Public Figure",
"disclaimer": "*Disclaimer: This user may have comment filtering turned on",
"slug": "hello-world",
"img" : "https://ilarge.lisimg.com/image/16801290/1080full-kylie-jenner.jpg",
"banner" : "https://i.pinimg.com/originals/a5/2b/96/a52b963809c7e64e538b113cccf61dda.jpg",
"handle": "kyliejenner",
"handlelink" : "https://www.instagram.com/kyliejenner/"
}
]
I am currently trying to make a GET request to an API(url) that also includes specific data from my json file. In this case it will include the celebs handle. This is what I have setup here on Graphs.js.
export default class Graph extends Component {
constructor(props) {
super(props);
}
state = {
handle: '',
}
componentDidMount() {
axios.get('http://localhost:5000/celebs/' + handle)
.then(response => {
this.setState({ celebs: response.data })
})
.catch((error) => {
console.log(error);
})
}
}
I am aware this isn't right as this is where I am stuck. "+ handle" is to come from the json file. I want to make a request to the url where /handle will match the handle directly from json file as defined "handle": "#kyliejenner". But I keep getting an error saying 'handle' is not defined no-undef. No matter how I do it, I can't seem to get it right and keep getting the same error.
So how do I go about defining handle with the data from the json file passed into it? More specifically the handle data.
I apologize in advance if this isn't clear. Please let me know if you need further clarrification.
You can store the json in a different file assign the data to an object and you can import it like this.
import posts from 'posts.js';
Now you have access to the posts object in your component, so you can just access it using
const handle = posts[i].handle; //pass the index of array(i);
As pointed in the comment by Sean, your local state is a bit wrong. You should declare it like this:
constructor(props) {
super(props);
this.state = {handle: ''};
}
And use it like this:
axios.get('http://localhost:5000/celebs/' + this.state.handle)
Or, using Template Literals:
axios.get(`http://localhost:5000/celebs/${this.state.handle}`)
More info in the docs: https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class

Accessing JSON object within Object using React/Axios

I’m working with an API that shows data for cryptocurrencies called CryptoCompare. I’m a React noob but I’ve managed to use Axios to do the AJAX request. However I’m having trouble accessing the JSON elements I want.
Here’s what the JSON looks like: https://min-api.cryptocompare.com/data/all/coinlist
Here is my request:
import React, { Component } from 'react';
import './App.css';
import axios from "axios";
var NumberFormat = require('react-number-format');
class App extends Component {
constructor(props) {
super(props);
this.state = {
coinList: []
};
}
componentDidMount() {
axios.get(`https://min-api.cryptocompare.com/data/all/coinlist`)
.then(res => {
const coins = res.data;
//console.log(coins);
this.setState({ coinList: coins});
});
}
// Object.keys is used to map through the data. Can't map through the data without this because the data is not an array. Map can only be used on arrays.
render() {
console.log(this.state.coinList.Data);
return (
<div className="App">
{Object.keys(this.state.coinList).map((key) => (
<div className="container">
<span className="left">{key}</span>
<span className="right"><NumberFormat value={this.state.coinList[key].CoinName} displayType={'text'} decimalPrecision={2} thousandSeparator={true} prefix={'$'} /></span>
</div>
))}
</div>
);
}
}
export default App;
I am able to output some JSON using console.log(this.state.coinList.Data);. It outputs the JSON object, but I am unable to console.log properties of the object itself.
How would I, for example, output the CoinName property of the first element 42?
console.log(this.state.coinList.Data.CoinName) doesn’t work
nor does console.log(this.state.coinList.Data[0].CoinName) etc…
You are iterating over this.state.coinList while you want to iterate over this.state.coinList.Data.
Try this:
render() {
const data = this.state.coinList.Data;
if (data == null) return null;
return (
<div className="App">
{Object.keys(data).map((key) => (
<div className="container">
<span className="left">{key}</span>
<span className="right"><NumberFormat value={data[key].CoinName} displayType={'text'} decimalPrecision={2} thousandSeparator={true} prefix={'$'} /></span>
</div>
))}
</div>
);
}
CodeSandbox here: https://codesandbox.io/s/3rvy94myl1
I also stumbled with that same problem as yours. You cannot access an object inside a data because it is empty when the render happens. What I did was I made a conditional render where if the data is empty, it will just show a loading screen or something like that. And when the data loads , it will access the object inside that data. I can now access the object inside because I waited for the data to load inside render.
I hope this answer can help future react users
return (
<div>
{this.state.coinList.length>0? <h1>{this.state.coinList[0].coinName}</h1>: "Loading"}
</div>
);
}
Added: To console.log the data , you can create a new component inside the conditional render. Inside that component, you can access all the data you want because it is rendered after the data is loaded.
You're might have to parse the JSON. Might be good to do that before you save it.
const coins = JSON.parse(res.data)

Accessing state in React render method after API request

I'm working on my first complicated React app and I am making a request to a movie API. My site allows the user to do a search in a searchbar for whatever movie, show, actor, etc... that they are searching for. I'm pulling the user's search query and inserting it into an api request like this:
export const getDetails = (id) => {
return new Promise(function(resolve, reject) {
axios.get(`https://api.themoviedb.org/3/movie/` + id +`?api_key=&language=en-US`)
.then(function(response) {
resolve(response)
})
.catch(function(error) {
reject(error)
})
})
}
I'm able to get the data like this and console.log it:
import React, { Component } from 'react';
import Header from '../header';
import {Link} from 'react-router-dom';
import axios from 'axios';
import Footer from '../Footer.js';
import Searchbar from '../header/searchbar.js';
import List from '../results/list';
import {getDetails} from '../api/getDetails';
class Detail extends Component {
constructor(props) {
super(props);
this.state = {
id: this.props.match.params.id,
result: null,
error: false,
}
}
componentWillMount() {
getDetails(this.state.id).then(function(response){
this.setState({result: response});
console.log(response.data.original_title);
console.log(response.data.homepage);
console.log(response.data.popularity);
console.log(response.data.release_data);
console.log(response.data.overview);
}.bind(this)).catch(function(err) {
this.setState({
result:"There was a problem loading the results. Please try again.",
error: true
})
}.bind(this))
}
render() {
return(
<div>
<Header/>
<div className="details-container">
<h2>Details: </h2>
</div>
</div>
)
}
}
export default Detail
Console.logging it in the componentWillMount function successfully logs the data but I am not able to access the data in the render function via something like {response.data.orginal_title). How would I render the data being logged in componentWillMount?
TLDR; You can access your state variables from within your render function via this.state. Something like: console.log(this.state.result.data.origin_title) outside of the jsx and {this.state.response.data.orginal_title} inside the jsx.
P.S. You are using the correct this.
The following are picky recommendations and explanations, feel free to disregard.
It's recommended to make requests for data in componentDidMount. That can be read here in the docs for componentDidMount.
You're using arrow functions already in your get details function, if you convert the rest of your functions to arrow functions you no longer have to explicitly bind this to each one; it's automatically set be the this of it's parent. See the "No Separate This" section in the MDN docs
If you don't need any of the header information I would save response.data into your state so you don't have to type as much when you want to access the data. this.state.result.original_title vs this.state.result.data.original_title. That's just me and I'm lazy.
axios does return a promise like Eric said so you don't actually need to wrap it in the extra promise. You can just straight up return it and since arrow functions automatically return one line expressions you can spiff that up into a one liner:
export const getDetails = id => axios.get(`https://api.themoviedb.org/3/movie/${id}?api_key=&language=en-US`)
Finally you should be able to access the data you've stored in your state from your render function as mentioned in #3 above. Outside of the JSX you can console.log it like normal console.log(this.state.result), inside your JSX, however, you will need to make sure you escape with {} like: <div>{this.result.original_title}</div>
Small working example here: https://codesandbox.io/s/zqz6vpmrw3
You can simply use
{this.state.result}
inside the render.

Angular 2 - Using/displaying JSON data fetched through HTTP, or mocked

I'm working on an Angular 2 application, and I'm trying to use JSON data, either local/mocked or fetched via HTTP, and display it on a component. I have an injectable service that will do the fetching/mocking -
import { Injectable } from 'angular2/core';
#Injectable()
export class TestService {
testString:string = "";
testDetails: string = "";
constructor() { }
getTestDetails(): Promise<string> {
this.testDetails = {
"status": "success",
"message": "Data save successful",
"data": {
"Random_Data_1": "Random Data 1",
"Random_Data_2": "Random Data 2"
}
};
return Promise.resolve(JSON.stringify(this.propertyDetails));
}
}
And then I have a component that uses the service via Dependency Injection -
import { Component, OnInit } from 'angular2/core';
import {TestService} from "./test.service";
#Component({
selector: 'test',
templateUrl: './test.component.html',
styleUrls: []
})
export class TestComponent implements OnInit {
testDetails: string = "";
constructor(private testService: TestService) { }
ngOnInit() {
this.display();
}
display(): void {
this.testService.getTestDetails()
.then(
testDetails => {
this.testDetails = JSON.parse(testDetails);
},
errorMessage => {
console.error("Something failed trying to get test details");
console.error(errorMessage);
}
);
}
}
The component HTML -
<div class="content">
<p> Test Details </p>
<p> {{ testDetails.data.Random_Data_1 }} </p>
</div>
The problem is, the HTML is erroring out trying to display the items in the testDetails JSON. I initially used it with md-tabs, so the first try would error out, but the other tabs would read the data fine. Also, the ngOnInit would be called twice when the error occurs. I have narrowed it down to the data coming in and the object types that is causing me the headache.
I know I can create a Details class and declare testDetails of type Details, and then map the JSON data into the class, but the thing is, I want to work with generic data, and only know a few components that will be present in the data. Is there a way to read the JSON, and use the data without having to define a separate class for each scenario ?
I have a plunker with the most basic stuff set up. The actual setup runs fine on my local system up until where I try to access the JSON data in the HTML, at which point the browser throws a cryptic error. The skeleton code doesn't even run on Plunker. That said, the structure in the Plunker defines the structure of my app and the data flow. Plunker with the basic setup
What is the best way to achieve this ? What is the standard/best practice to do this ?
Throwing another option out there, since you asked about best way to achieve this. Might not be the best idea, this is subjective ;) But if I were you...
Thinking about the future, where you will use real backend, it could be nice to use mock json file. If/when you move over to a real backend, you wouldn't basically need to change anything else but the url of the requests :)
So I set up a simple example for you. Here I used Observables, but you can use Promises if you prefer that. Here's more info on HTTP if you want/need to read up on that. Most important thing is that you have the HttpModule imported in your app module.
You have your file with JSON and in your service make http-requests to that:
getTestDetails() {
return this.http.get('src/data.json')
.map(res => res.json())
}
Your display-method:
display() {
this.testService.getTestDetails()
.subscribe(data => {
this.testDetails = data;
});
}
And in the template use the safe navigation operator to safeguard null/undefined values:
<div class="content">
<p> Test Details </p>
<p> {{ testDetails?.data?.Random_Data_1 }} </p>
</div>
Here's a
Demo
As said, this is to give another approach on how to implement the things you want to achieve, and this would probably be my preferred way :)
Use
<p *ngIF="testDetails.data.Random_Data_1 "> {{ testDetails.data.Random_Data_1 }} </p>
This is because there is no data initially.Hope this helps you.