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

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.

Related

Not sure how to display backend data in react app

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>
));

How to set interval in useEffect in React Functional Component

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
)
}, [])

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.

accessing the json data from axios call in vue

I setup a fake mocke server in postman to get som test data for my vue applikation. This is what i am getting from the server:
I want to access the data information but i am having hard time doing so. This is the code that i am using:
<template>
<div class="admin">
<h1>This is admin page area</h1>
<JsonEditor :objData="config" v-model="config" ></JsonEditor>
</div>
</template>
<script>
import{getConfig} from "../utils/network";
import Vue from 'vue'
import JsonEditor from 'vue-json-edit'
Vue.use(JsonEditor)
export default{
data: function () {
return {
config:{}
}
},
created:function(){
getConfig()
.then(response => {
console.log(response)
this.config = response;
})
.catch(err => {
console.log(err)
})
}
}
</script>
I have tried doing response.data but did not work. I am feeding this to the json editor but it is currently not being able to show the json. Its empty. This is my network call code:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
const getConfig = () =>{
return Vue.axios.get('https://8db51a11-752e-4d64-b237-8195055fbf26.mock.pstmn.io')
};
//Export getConfig so other classes can use it
export{
getConfig
}
What am i missing?
You can also try providing a then statement:
const getConfig = () =>{
Vue.axios.get('https://8db51a11-752e-4d64-b237-8195055fbf26.mock.pstmn.io').then(response => {
return response.data});
};