Unable to send api response data from express to react after refreshing the page - node.js

I'm learning react and node js with express framework and I'm working on a project where I need to retrieve API data from express to react.
I retrieved data from backend express js where I made a simple json value. My backend server.js code is given below.
server.js
const express = require('express')
const app = express()
const PORT = 3001;
app .get('/api/contents',(req,res)=>{
const contents=[
{
"id":0,
"heading":"Joshua Tree Overnight Adventure",
"content":"A sight in the blue sea..."
},
{
"id":1,
"heading":"Catch waves with an adventure guide",
"content":"Lorem.."
},
{
"id":2,
"heading":"Catch waves with an adventure guide",
"content":"Lorem epsum ..."
}
];
res.json(contents)
})
app.listen(PORT,()=>{
console.log("express server is running...")
})
In react app, I used axios to retrieve those values from backend and tried to pass the api values of content with id= 0 as props in "TheLatestArticles" component. I have updated proxy in package.json in react to connect backend. The below code is the mainhomepage component where it is enclosed with TheLatestArticles component with props value
MainHomePage.js
import axios from 'axios';
import {useState,useEffect} from 'react'
function MainHomePage(){
const [content,setContent]=useState([]);
useEffect(()=>{
const fetchPosts = async ()=>{
const res =await axios.get("/api/contents")
setContent(res.data)
console.log(res)
}
fetchPosts()
},[])
return (
<>
<TheLatestArticle content={content} />
</>
);
}
export default MainHomePage;
TheLatestArticle.js
import cardImage from "./../../Images/card.jpg"
import './TheLatestArticleCard.css';
const TheLatestArticleCard=(props)=>{
console.log(props)
return(
<>
<div className="card">
<div className="image">
<img src={cardImage} alt="cardimg"/>
</div>
<div className="content">
<p className="heading">{props.content.heading}</p>
<p className="body-content">{props.content.content}</p>
<div className="details">
<p className="details-info">Travel <span className="details-info-2">/ August 21 2017</span></p>
</div>
</div>
</div>
</>
)
}
export default TheLatestArticleCard;
When I run the application, It displayed all the api values in the screen given below.
I console.log the api values inside useEffect and it displayed all the api values perfectly.
But when I refresh the page, the api value became undefined and gave me this error
Can you please solve me this issue with the reason behind this error? Thanks a lot!

Try it like this
{(content && content.length > 0) && <TheLatestArticle content={content} />}
Since your API call is async there won't be any data in content initially. After a while, your API is called and data is fetched. Then you will have data. To prevent TheLatestArticle to blow up we add some conditions when to show that component. The error in the screenshot is when you try to use a property heading from content where content is empty.
Now with the condition, TheLatestArticle will not render until there is some data.
Update
You are using <TheLatestArticle content={content} /> and content is assumed to be an object. But as per your code, it's an array. If you are not already using content.map((c)=> <TheLatestArticle content={c} />) you should do that.

Related

Pulling Data From Node.js Rest Api Into React with axios

I am New to react, Node.js so I apologize if this is simple. I have been trying to pull Data From A Node.js Api Running Express into a React Component with Axios. I have tried many different ways and have searched for a solution with no luck. I am unable to access the Id as well as the ProductName
JSON DATA
{"Results":
[
{"id":4,"productName":"Flap Disc"}, {"id":5,"productName":"Fiber Disc"}
]
}
For whatever reason I am unable to Access the data inside these Objects.
CODE
export default function Parent () {
const [products, setProducts] = React.useState('');
const url = 'http://localhost:3040/';
React.useEffect(()=>{
async function getProduct(){
const response = await axios.get(`${url}`);
const a = (response.data.Results)
setProducts(a.map((item)=>
{item}
))
}
getProduct()
}, [])
return(
<div>
{
console.log(products)
}
</div>
)
}
Logging out inside JSX won't do anything. What you want to do is map over the data and display it as a component. Change your return to something more like this
return (
<div>
{products?.map((product) => <p>{product.name}<p>)
</div>
)
You should also change the default value fo products from an empty string to an empty array
const [products, setProducts] = React.useState([])

Rendering react component on express route

I have an application which uses the express server and the create-react-app front-end. The structure looks like this. ( Not including all the files in the structure - only the ones that matters )
Client-
build
etc
public
src-
assets
components-
landing-
landing.js
github-
github.js
steam-
steam.js
App.js
index.js
routes-
routes.js
index.js
My index.js file is starting the express server and is as following-
const express = require( 'express' );
const app = express();
const PORT = process.env.PORT || 5000;
require('./routes/routes')( app );
app.use( express.static( 'client/build' ));
app.listen( PORT, () => {
console.log( "Server is running on port 5000 " );
});
The route file on the server side is as follows-
module.exports = ( app ) => {
app.get( '/', ( req, res ) => {
console.log("Hello");
res.send( "Hello" );
});
app.get( '/steam', ( req, res ) => {
res.send( "Place for Steam!!");
});
app.get( '/github', ( req, res ) => {
res.send("Place for Github!!");
});
}
My app.js file
class App extends Component {
render() {
return (
<div className="App">
<BrowserRouter>
<div className="container">
<Route path="/" component={ Landing }/>
<Route path="/steam" exact component={ Steam } />
<Route path="/github" exact component={ Github } />
</div>
</BrowserRouter>
</div>
);
}
}
export default App;
On my client side, my main concerned file in landing.js which is as follows.
class Landing extends Component{
render(){
return(
<div className="container">
<div className="row">
<div className="col-md-6">
<div className="bg">
<img src="https://www.bleepstatic.com/content/hl-images/2016/12/23/Steam-Logo.jpg" alt="" />
<div className="overlay">
Steam Info
</div>
</div>
</div>
<div className="col-md-6">
<div className="bg">
<img src="https://linuxforlyf.files.wordpress.com/2017/10/github-universe1.jpg" alt="" />
<div className="overlay">
Github Info
</div>
</div>
</div>
</div>
</div>
)
}
}
export default Landing;
In the above component, the thing that i care about is the a tag which leads to the either /steam or /github express route, which is intentional cause i want to reload the page and on the page I am only getting the res.send data, which makes sense cause that's an express route. But I want to render my steam component on /steam route. ( same with github ). I was hoping my BrowserRouter in App.js would change the component based on the route, but It's not. I am, only getting the express data. How can I render my Steam react component on the express '/steam' route. Clearly I am mixing the server and client side in weird way.
Simply use res.render('index'); for all backend routes.
Here we are building a single-page app with react, which means there's only one entry file (only one html file, usually index.html), the page renders differently because our js code checks the url and decides what to show (which frontend route to use). They all happend after the browser receives the html file along with the js/css files included. All the backend has to do when receiving a page request, is to send the same html file (and js/css files after the html is parsed by browser). Of course for data/xhr requests and invalid requests, we need to send data and 404.html accordingly.

Fetching API from react sending me wrong URL

Learning React.js and Node.js and making a simple crud app with Express API on the back-end and React.js on the front end.
App.js of my React.js looks like this.
`import React, { Component } from 'react';
import './App.css';
import Rentals from './components/Rentals';
import Idpage from './components/Idpage';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
class App extends Component {
render() {
return (
<div className="mainappdiv">
<Router>
<main>
<Route exact path="/" component={Home} />
<Route exact path="/rentals" component={Rentals} />
<Route path="/rentals/:propertyid" component={Idpage} />
</main>
</div>
</Router>
</div>
);
}}
export default App;
I am making an app that when if you go to /rentals, it will fetch the data and print stuff. This is currently working and all the data from my database is rendering.
Now I am trying to go to /rentals/1 or /rentals/2 then trying to print only listings of that id.
import React, { Component } from 'react';
class Idpage extends Component {
componentDidMount() {
fetch('api/listofrentals/2')
.then((response)=>{
console.log(response)
return response.json()
})
.then((singlerent)=>{
console.log(singlerent)
})
}
render() {
return (
<div>
<p>this is the id page solo</p>
<p>{this.props.match.params.propertyid}</p>
</div>
);
}}
export default Idpage;
When I do this, I get an error saying GET http://localhost:3000/rentals/api/listofrentals/2 404 (Not Found)
I am trying to fetch from the URL http://localhost:3000/api/listofrentals/2 and do not understand why the "rentals" part is in the url.
My React server is running on localhost:3000 and node.js is running on localhost:30001. And my React's package.json has this "proxy": "http://localhost:3001/"
Fetch by default will access a relative path to where you are using it. You can specify you want to bypass the relative path by starting your url with /.
fetch('/api/listofrentals/2')
In case if you want to change the base url for testing. You can turn off web security in Google and use.
In ubuntu command line it is
google-chrome --disable-web-security --user-data-dir

React w/SignalR - TypeError: WebSocketClient() not a constructor

new to React development.
I am building an API client for the BitTrex Exchange API, using their node.js wrapper: node.bittrex.api
With the objective of simply testing the websocket subscription for orderbook updates within the ReactJS framework, here are the steps I have taken:
-Used create-react-app to create the app.
-used npm to install the node.bittrex.api
-added the bittrex client object to the top of the default App.js component and configured options with proper API keys
-added a button (with handler, binded to the button according to React docs) to the default App.js main component,
-inside the handler function, initiated the websocket subscription according to the example code in the node.bittrex.api docs.
The app comes up, but when I press the button, I get an error saying that TypeError Websocketclient() is not a constructor, in the line inside the SignalR.js that creates the websocket connection:
Now I suspect that there is just something specific with the React framework that is screwing this up. Can anyone please help me understand the intricacies? Thanks. Here is my App.js:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
var bittrex = require('../node_modules/node.bittrex.api/node.bittrex.api.js');
bittrex.options({
'apikey' : process.env.REACT_APP_BTREX_API_KEY,
'apisecret' : process.env.REACT_APP_BTREX_SECRET_KEY,
'verbose' : true,
'cleartext' : false,
'baseUrl' : 'https://bittrex.com/api/v1.1'
});
class App extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
bittrex.websockets.subscribe(['BTC-ETH','BTC-ANS','BTC-GNT'], function(data) {
if (data.M === 'updateExchangeState') {
data.A.forEach(function(data_for) {
console.log('Market Update for '+ data_for.MarketName, data_for);
});
}
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<br/>
<button onClick={this.handleClick}>Start WS Sub</button>
</div>
);
}
}
export default App;

Checksum Invalid - SSR props to Client

I'm using the react engine react-engine on GitHub to create a node, express app with react for the views.
For the most part, my app is rendered on the server. However, on one page/express route I require the view to be rendered server-side and then for the React to be fully interactive on the client.
So far I've got the view rendering server-side and then being re-loaded/re-mounted by React on the client.
My problem is that I'm now getting the following error:
bundle.js:357 Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) <section data-reactroot="" data-reactid
(server) <section cl
Here's what my code looks like:
class FormCreate extends React.Component {
render() {
return (
<ReactBlank title="Create new application form" messages={this.props.messages} authUser={this.props.authUser}>
<script dangerouslySetInnerHTML={{
__html: 'window.PROPS=' + JSON.stringify(this.props)
}} />
<div id="app-content">
<Main {...this.props}/>
</div>
</ReactBlank>
);
}
}
FormCreate.propTypes = {
messages: React.PropTypes.array,
authUser: React.PropTypes.object,
form: React.PropTypes.object
};
module.exports = FormCreate;
The above is initially rendered on the server and then the following re-mounts it on the client:
var React = require('react');
var ReactDOM = require('react-dom');
var Main = require('./app/views/shared/builder/Main.jsx');
document.addEventListener('DOMContentLoaded', function onLoad() {
const propScript = document.getElementById('react-engine-props');
const props = window.PROPS;
ReactDOM.render(
<Main {...props} />,
document.getElementById('app-content')
);
});
Can anyone see a problem here?

Resources