Not sure how to display backend data in react app - json

I have data that shows up as following in my backend server-
I want to show this data as frontend.
I did it the following way-
import {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [data,setData] = useState([])
useEffect( () => {
fetch("http://127.0.0.1:5000/lang")
.then(res => res.json())
.then( res => {setData(res)} )
console.log('datas')
console.log(data)
}, [] )
return (
<div className="App">
{
data.map((data,i) => {
<h1>
Edit {data.name} and save to reload.
</h1>
})
}
</div>
);
}
export default App;
This data is being console logged in the background, but it won't show up in the frontend app.
How would I have the backend data display here?

You need to either return the element
data.map((data,i) => {
return (
<h1>
Edit {data.name} and save to reload.
</h1>
)
})
Or use parentheses
data.map((data,i) => (
<h1>
Edit {data.name} and save to reload.
</h1>
));

Related

Way to display individual data from MySQL database on React.js?

Is there a way that individual data from the MySQL database will be displayed on the react.js pages, like user profile?
This is my user profile but it display all the data on the database. How I can display single data? For example the information of the Student number 1. const getStudent is where the connection happen from the backend
Front end
import React from "react";
import { useState } from "react";
import Axios from "axios";
import { useNavigate } from "react-router-dom";
function Profile() {
const [studentList, setStudentList] = useState([]);
let navigate = useNavigate();
const getStudent = () => {
Axios.get("http://localhost:3001/students").then((response) => {
setStudentList(response.data);
});
};
return (
<div className="students">
<button onClick={getStudent}>Show Students</button>
<h3>
</h3>
{studentList.map((val, key) => {
return (
<div className="student">
<div>
<h3>Email: {val.email}</h3>
<h3>Password: {val.password}</h3>
<h3>Student Number: {val.student_num}</h3>
<h3>First Name: {val.first_name}</h3>
<h3>Middle Name: {val.middle_name}</h3>
<h3>Last Name: {val.last_name}</h3>
<h3>Year Level: {val.year_lvl}</h3>
<h3>Section: {val.section}</h3>
</div>
</div>
);
})}
</div>
);
}
export default Profile;
key is the name of the column
The connection of the mysql/ BackEnd
app.get("/students", (req, res) => {
db.query("SELECT * FROM student", (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});

How to display JSON data in an html element using redux-thunk store

I am trying to use Redux and redux-thunk middleware to modify state change and make use of async actions to send data and receive data from the server. I created my own rails api which is returning the JSON data in the console.log of my webpage but Im wondering how to render this data in a div in my html. I realize this may not be coded in the best way, any help with re-writing would be appreciated too!
Here is the start of my app.js file
import React from "react";
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
import "./assets/style.css";
import Quiz from "./components/quiz"
import Home from "./components/home";
import Result from "./components/Result";
import { useEffect } from "react";
function App() {
useEffect (() => {
fetch("http://127.0.0.1:3000/questions")
.then(resp => resp.json())
.then(console.log);
},[])
return (
<div className="App">
<Router>
<Switch >
<Route exact path="/">
<Home />
</Route>
{ <Route exact path="/quiz">
<Quiz/>
</Route>}
<Route exact path="/result">
<Result />
</Route>
</Switch>
</Router>
</div>
);
}
export default App
Here is my index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from 'react-redux';
import { createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import quizReducer from './store/reducers/reducer'
import "./assets/style.css";
import App from "./App";
const store = createStore(quizReducer, applyMiddleware(thunk))
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
)
Here are my action/reducer
actions.js
export const getQuestion = (question) => ({type: "GOT_QUIZ", payload: question})
export const fetchQuestion = () => {
return (dispatch) => {
fetch(url)
.then(resp => resp.json())
.then(question => {
dispatch(getQuestion(question))
})
}
}
export const createQuestion = (question) => {
return () => {
const configObj = {
method: 'POST',
question: JSON.stringify(question)
}
fetch(url, configObj)
.then(resp => resp.json())
.then(json => {
console.log(json)
})
}
}
reducer.js
export default function quizReducer(state = {questionBank: []}, action){
switch (action.type){
case "GOT_QUIZ":
return {...state, questionBank: action.payload}
default:
return state
}
}
Assuming that your reducer and actions are correct, you need to do two things in your components.
1) Initialize the Fetch
import {useDispatch} from 'react-redux';
import {fetchQuestion} from './actions';
const dispatch = useDispatch();
useEffect (() => {
dispatch(fetchQuestion());
}, []);
This will call your fetchQuestions thunk once when the component is first mounted.
2) Access the Data
import {useSelector} from 'react-redux';
const questions = useSelector(state => state.questionBank);
This will access the array of questions from your store and automatically respond to changes when the store state is updated.
Perhaps step 1 goes in App and step 2 goes in Quiz and Result. Or perhaps both steps go in App and you pass down the data through props.

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;

JSON data from S3 text file using React

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;

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.