How to set interval in useEffect in React Functional Component - mysql

import './App.css';
import { useState, useEffect } from 'react'
import Axios from 'axios'
function App() {
const [list, setList] = useState([]);
useEffect(() => {
Axios.get('http://localhost:3001/getdata').then((response) => {
setList(response.data)
});
})
return (
<div className="App">
<div className="container">
{list.map((val, key) => {
return <div className="row">{val.Tweet}</div>
})}
</div>
</div>
);}
export default App;
The above code fetches the data infinitely from my MySQL database, how can I modify it to fetch the data after a certain interval?

Use setInterval
useEffect(() => {
setInterval(
() => Axios.get('http://localhost:3001/getdata').then((response) => {
setList(response.data)
}),
5000 // 5seconds
)
}, [])

Related

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;

Trying to fetch a specific record in JSON file

I am trying to fetch just one record from my JSON file, the JSON file is in the public folder
I set up a codesandbox https://codesandbox.io/live/7gu09fv
What is happening now is that it just returns the first record from the JSON and isn't matching the id to pageId
import React, { useState, useEffect } from 'react';
import {
useLocation
} from "react-router-dom";
function FetchContent( { pageId } ) {
const [page, setPage] = useState([]);
useEffect(() => {
fetch("pages.json" ,{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(json =>{
setPage(json)
}
)
}, []);
const found = page.find(id => id = { pageId });
if (!found) return <div />;
return (
<>
<h1 key={found.id}>{found.title.rendered}: {found.id} : {pageId}</h1>
</>
);
}
function Page() {
const { state: { pageId } } = useLocation();
return (
<div className="container-fluid">
<FetchContent pageId={pageId} />
</div>
);
}
export default Page;
import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
function FetchContent({ pageId }) {
const [foundItem, setFoundItem] = useState();
useEffect(() => {
fetch("pages.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
})
.then((res) => res.json())
.then((json) => {
const found = json.find(({id}) => (id === pageId));
setFoundItem(found);
});
}, [pageId]);
if (!foundItem) return <div />;
return (
<>
<h1 key={foundItem.id}>
{foundItem.title && foundItem.title.rendered ? foundItem.title.rendered: ''}: {foundItem.id} : {pageId}
</h1>
</>
);
}
function Page() {
const location = useLocation();
const [pageId, setPageId] = useState(null);
useEffect(()=> {
if(location.state){
setPageId(parseInt(location.state.pageId, 10));
}
}, [location]);
return (
<div className="container-fluid">
<FetchContent pageId={pageId} />
</div>
);
}
export default Page;
Try this:
const found = page.find(obj => obj.id === pageId);

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.

Not able to fetch data from API endpoint in ReactJS?

I have created REST API endpoint i.e localhost:5000/api/match/:match_idNow I want to fetch data from this endpoint and display it on frontend but I am getting undefined error.
In server.js :
//Get a particular match stats
app.get('/api/match/:match_id', (req, res) =>{
let match = req.params.match_id;
matches.findOne({id: parseInt(match)}).then(Match =>{
res.json(Match);
});
});
In matchinfo.js :
import React, { Component } from 'react';
class Matchinfo extends Component {
constructor(props){
super(props);
this.state = {
info:[],
loading:true
};
}
componentDidMount(){
fetch('api/match/:match_id')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
info:res,
loading:false
})
})
}
render() {
if (this.state.loading) {
return <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" />
}
return (
<div>
<p class="match">MATCH {info.id}</p>
<h4>{info.team1}</h4>
<p>VS</p>
<h4>{info.team2}</h4>
<div class="winner">
<h3>WINNER</h3>
<h4>{info.winner}</h4>
</div>
</div>
);
}
}
export default Matchinfo;
In matchinfo component I am getting failed to compile after loader is finished spinning see screenshot for more clarification.
JSON Response :
Try below updated code. It should work as you expected
import React, { Component } from 'react';
class Matchinfo extends Component {
constructor(props){
super(props);
this.state = {
info:[],
loading:true
};
}
componentDidMount(){
fetch('api/match/:match_id')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
info:res,
loading:false
})
})
}
renderLoading(){
<img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" />
}
render() {
const {info} = this.state;
return (
<div>
{this.state.loading ? this.renderLoading(): ''}
{this.state.info.length > 0 && (
<div>
<p class="match">MATCH {info.id}</p>
<h4>{info.team1}</h4>
<p>VS</p>
<h4>{info.team2}</h4>
<div class="winner">
<h3>WINNER</h3>
<h4>{info.winner}</h4>
</div>
</div>
)}
</div>
);
}
}
export default Matchinfo;