I am trying to render some JSON about a person's location from an api in my react app.
I am using isomorphic-fetch to access the data from the API I can add the base test in and it correctly logs the data using below.
require('isomorphic-fetch');
require('es6-promise').polyfill();
var url = 'http://localhost:3000/api/data'
fetch(url)
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(data) {
console.log(data);
});
What i'm trying to work out is how I can take this response and render it in my component which currently looks like this (in this example code below data is coming from local json file so i need to merge them together).
I've attempted to set up componentDidMount but could get my head around the syntax so it kept breaking, I also checked out redux actions but that exploded my brain.
const personLoc = Object.keys(data.person.loc).map((content, idx) => {
const items = data.person.loc[content].map((item, i) => (
<p key={i}>{item.text}</p>
))
return <div key={idx}>{items}</div>
})
export default function PersonLocation() {
return (
<div className="bio__location">
{personLoc}
</div>
)
}
js import { useEffect, useState } from "react"; import "./App. css"; function App() { const [data, setData] = useState([]); const fetchData = () => { fetch(`https://dummyjson.com/products`) . then((response) => response. json()) .
To get JSON from the server using the Fetch API, you need to use the JavaScript fetch() method. Then you need to call the response. json() method to get the JSON. The "Accept: application/json" header tells the server that the client expects a JSON response.
Create a function getData() that uses JavaScript's fetch API to fetch local JSON and call it from inside useEffect, as seen below. 'data. json' or './data. json' should be the path to your JSON file.
To load JSON from file, you have to have the raw . json file saved in your /src directory. In Create React App, you can directly import the JSON file and it will work as if it were a JS object, no need to parse it again. To load JSON from file, import it into your component.
componentDidMount should setState:
componentDidMount() {
var that = this;
var url = 'http://localhost:3000/api/data'
fetch(url)
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(data) {
that.setState({ person: data.person });
});
}
The render component should map the state:
const personLoc = Object.keys(this.state.person.loc).map((content, idx) => {
const items = this.state.person.loc[content].map((item, i) => (
<p key={i}>{item.text}</p>
))
return <div key={idx}>{items}</div>
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With