JSON data from S3 text file using React - json

I'm trying to get JSON data from an s3 bucket using React (in a Gatsby project).
This is my code.
import React from 'react';
function getJson() {
return fetch("http://secstat.info/testthechartdata.json")
.then((response) => response.json())
.then((responseJson) => {
return <div>{responseJson[0]}</div>;
})
.catch((error) => {
console.error(error);
});
};
export default getJson;
This is the error I get.
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
How should I do this? There is probably an easy way to do this in Gatsby but I was going to use React.

Your code has 2 issues:
You can't return a component that waits to Promise.
Fetching a cross domain assets will require CORS headers in your S3
You should refactor it to something like this:
import React, { useState, useEffect } from 'react';
function getJson() {
return fetch('http://secstat.info/testthechartdata.json')
.then(response => response.json())
.catch(error => {
console.error(error);
});
}
const MyComp = () => {
const [list, setList] = useState([]);
useEffect(() => {
getJson().then(list => setList(list));
}, []);
return (
<ul>
{list.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
export default MyComp;

Related

How to use data from a api (json) in react

I am making a simple weather app with react and typescript.
I want to know how to display simple data fetched from a public api in react and typescript. This api is in a json format. URL(https://data.buienradar.nl/2.0/feed/json)
How do you use api data in react?
What I have tried is calling the get forecast function inside a paragraph.
<p>Forecast: {getForecast} </p>
Source code of the forecast component.
import React from 'react';
const Forecast = () => {
function getForecast() {
return fetch("https://data.buienradar.nl/2.0/feed/json")
.then((response)=> response.json())
.then((data) => {return data.forecast})
// .then((data) => {return data});
.catch((error) => {
console.log(error)
})
}
return (
<div>
<h2>Take weatherdata from the api</h2>
<div>
</div>
<button onClick={getForecast}>Take weather data from the api</button>
<p>Forecast: {getForecast}</p>
</div>
)
}
export default Forecast;
UseState() is the react hook method, which helps to achieve it. Check the below code for reference.
import React, { useState } from 'react';
const Forecast = () => {
const [forecast, setForecast] = useState();
function getForecast() {
return fetch("https://data.buienradar.nl/2.0/feed/json")
.then((response)=> response.json())
.then((data) => {return setForecast(data.forecast)})
// .then((data) => {return data});
.catch((error) => {
console.log(error)
})
}
return (
<div>
<h2>Take weatherdata from the api</h2>
<div>
</div>
<button onClick={getForecast}>Take weather data from the api</button>
<p>Forecast: {forecast}</p>
</div>
)
}
export default Forecast;

How can I turn a function used in many components into its own component which I can reuse across the app?

I have a fetch request used on multiple pages, and would like to turn it into a component to simply call in whenever it's needed. This is proving to be harder than I thought, and it's bring up a number of issues.
I have tried using the wrappedComponent function but not sure if that's the solution as it's still not working. It's now saying that the fetchPosts class constructor cannot be invoked without new.
const that = this;
fetch ('/testrouter')
.then (response => {
return response.json();
}).then(jsonData => {
that.setState({posts:jsonData})
}).catch(err => {
console.log('Error fetch posts data '+err)
});
}
This is what I want to turn into a component, so that I can just call it by it's name from another one inside componentDidMount. I have tried doing this:
function fetchPosts(WrappedComponent) {
class FetchPosts extends Component {
constructor(props) {
super(props)
this.state = {
posts: []
}
}
fetchAllPosts() {
const that = this;
fetch ('/testrouter')
.then (response => {
return response.json();
}).then(jsonData => {
that.setState({posts:jsonData})
}).catch(err => {
console.log('Error fetch posts data '+err)
});
}
render() {
return (<WrappedComponent
fetchAllPosts = {this.fetchAllPosts})
/>);
}
}
return FetchPosts;
}
export default fetchPosts
Then importing it and calling it with fetchPosts but it's not working.
I was hoping I would be able to create a component, add the code then import the component, but this is not working.
You might want to create a custom hook to do this:
useFetch.jsx
import React, { useState, useEffect } from 'react'
const useFetch = (url) =>
const [state, setState] = useState({ loading: true, data: null, error: null })
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => setState(state => ({ ...state, loading: false, data }))
.catch(error => setState(state => ({ ...state, loading: false, error }))
},[])
return state
}
export default useFetch
MyComponent.jsx
import React from 'react'
import useFetch from './useFetch.jsx'
const MyComponent = () => {
const data = useFetch('/testrouter')
return (<>
{ data.loading && "Loading..." }
{ data.error && `There was an error during the fetch: {error.message}` }
{ data.data && <Posts posts={data.data}/> }
</>)
}

TypeError: Cannot read property 'map' of undefined REACTjs problem

This code constantly gives me error that cannot read property map of undefined, i am simply trying to fetch some data from the database
import React, { Component } from 'react';
import './App.css';
class App extends Component {
state={
products:[]
}
componentDidMount(){
this.getProducts();
}
getProducts = _ =>{
fetch('http://localhost:8000/products')
.then(response => response.json())
.then(response => this.setState({products: response.data}))
.catch(err=>console.error(err))
}
renderProduct=({product_id,name})=> <div key={product_id}>{name}</div>
render() {
const{products}=this.state;
return (
<div className="App">
{products.map(this.renderProduct)}
</div>
);
}
}
export default App;
The server side send code
app.get('/products', function (req, res) {
connection.query('SELECT * FROM prod', function (error, results, fields) {
if (error) throw error;
res.send(results);
});
});
The main issue is in getProducts, you need to make sure response.data.products exists it might have another name. Check the console.log(data).
getProducts = _ =>{
fetch('http://localhost:8000/products')
.then(response => response.json())
.then(data => this.setState({products: data.products }) || console.log(data))
// data is an object you need to pick the correct key
.catch(err=>console.error(err))
}
You should check whether there are any products available in the array.
render() {
const{products}=this.state;
return (
<div className="App">
{products.length ? products.map(this.renderProduct) : 'No products available'}
</div>
);
}
Is it likely that your CRUD in the database is returning a Null, Undefined value or the server send a object and not a array, which causes your state to be updated in the componetDidMount with data that is not an array, hence the problem?

Pass database data from express.js server to react.js component

This is a react app with an express.js backend. I have a mysql database connected to my server.js file and it seems to be connected fine. My issue is I want to pass that data to my react app and display it there.
My server.js database connection
app.get('api/listitems', (req, res) => {
connection.connect();
connection.query('SELECT * from list_items', (error, results, fields) => {
if (error) throw error;
res.send(results)
});
connection.end();
});
So this should grab the 'list_items' records from the database
Below is my react.js code. I would like to display the records under the grocery list h3.
import React, { Component } from 'react';
import './App.scss';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: ['first item']
};
}
render() {
return (
<div className="App">
<h3>Grocery List</h3>
{this.state.data}
</div>
);
}
}
export default App;
I know this is a simple concept but I am new to backend development. The tutorials I have found have gotten me to this point, but I have had an issue finding one that simply explains how to pass and display data from the backend to frontend.
**index.js**
import React from 'react';
import { render } from 'react-dom';
import App from './components/app';
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux';
import store, { history } from './store';
const route = (
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
)
render(route,document.getElementById('app'))
**action/listItemAction.js**
export const ListItemSuccess = (data) => {
return {type: 'GET_LIST_ITEMS'};
}
export const getListItems = () => {
return (dispatch) => {
return axios.get('http://localhost:5000/api/listitems')
.then(res => {
dispatch(ListItemSuccess(res));
})
.catch(error=>{
throw(error);
})
};
}
**reducers/listItems.js**
const listItems = (state = [], action) => {
switch(action.type){
case 'GET_LIST_ITEMS':
return action.res.data;
default:
return state;
}
}
export default listItems;
**store.js**
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk'
import listItems from './reducers/listItems.js';
const store = createStore(listItems, compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
));
export default store;
**App.js**
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import './App.scss';
import getListItems from './action/listItemAction.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true,
};
}
componentWillMount() {
this.props.getListItems().then(() => {
this.setState({data: this.props.listItems, isLoading:false});
}).catch(error => {
throw(error);
});
}
render() {
return (
<div className="App">
<h3>Grocery List</h3>
{this.state.isLoading ? <p>Loading...</p>
: this.state.error ? <p>Error during fetch!</p>
: (
<ul>
this.state.data.map(item => <li>{item}</li>)
</ul>
)}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
listItems: state.listItems
};
};
const mapDispatchToProps = (dispatch) => {
return {
getListItems: bindActionCreators(getListItems, dispatch),
};
};
export default connect(mapStateToProps,mapDispatchToProps)(App);
You want to make a GET request to your backend to asynchronously fetch the data. If you want the data when your App component first mounts, you can use fetch in componentDidMount to call to your backend endpoint. Here's an example, with a loading fallback and basic error handling:
class App extends Component {
state = {
data: [],
loading: true,
error: false
}
...
componentDidMount() {
// Pick whatever host/port your server is listening on
fetch('localhost:PORT/api/listitems')
.then(res => { // <-- The `results` response object from your backend
// fetch handles errors a little unusually
if (!res.ok) {
throw res;
}
// Convert serialized response into json
return res.json()
}).then(data => {
// setState triggers re-render
this.setState({loading: false, data});
}).catch(err => {
// Handle any errors
console.error(err);
this.setState({loading: false, error: true});
});
}
render() {
return (
<div className="App">
<h3>Grocery List</h3>
// The app will render once before it has data from the
// backend so you should display a fallback until
// you have data in state, and handle any errors from fetch
{this.state.loading ? <p>Loading...</p>
: this.state.error ? <p>Error during fetch!</p>
: (
<ul>
this.state.data.map(item => <li>{item}</li>)
</ul>
)}
</div>
);
}
}
fetch won't reject on HTTP error status (404, 500), which is why the first .then is a little odd. The .catch will log the response here with the status, but if you want to see the error message from the server, you'll need to do something like this:
if (!res.ok) {
return res.text().then(errText => { throw errText });
}
See See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch for more information, or explore other data fetching libraries like axios.

Making an API call in React

I am trying to make an API call in React to return JSON data but I am a bit confused on how to go about this. My API code, in a file API.js, looks like this:
import mockRequests from './requests.json'
export const getRequestsSync = () => mockRequests
export const getRequests = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(mockRequests), 500)
})
It is retrieving JSON data formatted like this:
{
"id": 1,
"title": "Request from Nancy",
"updated_at": "2015-08-15 12:27:01 -0600",
"created_at": "2015-08-12 08:27:01 -0600",
"status": "Denied"
}
Currently my code to make the API call looks like this:
import React from 'react'
const API = './Api.js'
const Requests = () => ''
export default Requests
I've looked at several examples and am still a bit confused by how to go about this. If anyone could point me in the right direction, it would be greatly appreciated.
EDIT: In most examples I've seen, fetch looks like the best way to go about it, though I'm struggling with the syntax
Here is a simple example using a live API (https://randomuser.me/)... It returns an array of objects like in your example:
import React from 'react';
class App extends React.Component {
state = { people: [], isLoading: true, error: null };
async componentDidMount() {
try {
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
this.setState({ people: data.results, isLoading: false });
} catch (error) {
this.setState({ error: error.message, isLoading: false });
}
}
renderPerson = () => {
const { people, isLoading, error } = this.state;
if (error) {
return <div>{error}</div>;
}
if (isLoading) {
return <div>Loading...</div>;
}
return people.map(person => (
<div key={person.id.value}>
<img src={person.picture.medium} alt="avatar" />
<p>First Name: {person.name.first}</p>
<p> Last Name: {person.name.last}</p>
</div>
));
};
render() {
return <div>{this.renderPerson()}</div>;
}
}
export default App;
Does it make sense? Should be pretty straight forward...
Live Demo Here: https://jsfiddle.net/o2gwap6b/
You will want to do something like this:
var url = 'https://myAPI.example.com/myData';
fetch(url).then((response) => response.json())
.then(function(data) { /* do stuff with your JSON data */})
.catch((error) => console.log(error));
Mozilla has extremely good documentation on using fetch here that I highly recommend you read.
The data parameter in the second .then will be an object parsed from the JSON response you got and you can access properties on it by just using the property label as was in the JSON. For example data.title would be "Request from Nancy".
If you are struggling with fetch, Axios has a much simpler API to work with.
Try this in your API.js file (of course install axios first with npm i --save axios):
import axios from 'axios'
import mockRequests from './requests.json'
export const getRequests = (url) => {
if (url) {
return axios.get(url).then(res => res.data)
}
return new Promise((resolve, reject) => { // you need to return the promise
setTimeout(() => resolve(mockRequests), 500)
})
})
In your component, you can access the getRequests function like so
import React, { Component } from 'react'
import { getRequests } from './API.js'
class App extends Component {
state = {
data: null
}
componentWillMount() {
getRequests('http://somedomain.com/coolstuff.json').then(data => {
console.log(data)
this.setState({ data })
})
}
render() {
if (!this.state.data) return null
return (
<div className='App'>
{this.state.data.title}
</div>
)
}
}
export default App