axios get request for real-time data - node.js

For simplicity assume that I have entity user and in my frontend side (react) I am making an Axios get request to get all users to display them.
In the componentDidMount I am doing a get request const res = axios.get(myurl) then map the res to be displayed.
However, if a new user is entered in the database I have to refresh the page to see the update.
Here is my question, how to make the get request to be like running or something like this so if any changes happens in the database it reflects the get request.

You can use the useEffect in react
import React,{useEffect}from 'react'
function getAllUsers(){
//your code here...
}
useEffect(()=>{
getAllUsers();
})

This is a real-time updates, and we have multiple practices for such a case.
Before reading the answer, you need to know that this case is about the real-time updates concept and not a problem with a line of code solution. You need to implement real-time system in your app to achieve what you want.
1st Practice
Is to use a real-time library like Socket.io, so that you can listen to the events you want.
You can find here an example for Node.JS with React.JS
2nd Practice
Is to use a database that provides real-time updates like Firebase. Here you can find an example.

Related

How to structure external API calls for Node.js, express, ejs routing?

//API Call one
function receiveLocation(){
axios({
"method":"GET",
"url":"https://ip-geo-location.p.rapidapi.com/ip/check",
...
})
.then((response)=>{
return response.data.country.name;
})
.catch((error)=>{
console.log(error)
})
}
//API Call two
//API Call three
console.log(receiveLocation());
app.get("/", function(req,res){
var location = receiveLocation();//
//Then render all the data from my API calls such as location, currency,
//etc. in my landing page. Also use that data on the backend.
res.render("landing",{location:location});
});
I am currently trying to make a website that uses multiple API calls to get information such as location, currency, and other things of a user who loads the website.
I am attempting to receive all the information from the different API calls as I go through the get request route that allows a user to see the landing page. Firstly, I am not even sure if this is allowed. If it is allowed/standard practice, what am I doing wrong in this example. I am attempting to call a function that in the get route to the root page that returns the country of a visiting user. But after doing some console.log() debugging I see that that information is never being received in the get route. Last note: I want to use the info from the API calls both to change what the user sees, and for some calculations that would need to be run on the backend.
If this is not allowed/not standard practice, may someone explain what I should do instead/point in the right direction as to what I should learn to get a better understanding of what I am trying to do
What you are trying at the moment to do is not standard practice, you should lookup MVC for Express,there you will learn how to structure your backend code so that the GET Routes will be used as Views ( these will be your server getting some public files like html,css,javascript that will be passed some information from the Controllers,this is done by using some server-side renders like EJS).
I recommend taking this Udemy course https://www.udemy.com/course/nodejs-the-complete-guide/ for a full understanding,but if you don't have the time,lookup node.js mvc with express, there is plently information about this.

React JS isomorphic render

ReactJS, original Flux, react-router, nodeJS, socket.io
Everything is up to date.
If i'm switching off javascript in browser, only static code is being rendered.
During server side render ComponentWillMount and render methods being fired up, but not ComponentDidMount.
Even if I'm putting Flux logic into ComponentWillMount method, nothing happen: action is called, but socket.io doesn't send request to server to get data from database. Which means, no data being retrieved from database and nothing useful for search engines is being rendered.
If javascript is enabled, everything works perfect.
Here the important pieces of code:
Component. Add listener and call action:
componentDidMount() {
StoreUser.addChangeListener(this._onChange);
Actions.getUser(this.props.params.userid)
}
Client's action asks server for user data:
function _getUser (userid) {
socket.emit('getUser', userid)
}
up until this place server-side rendering works, but server itself doesn't received getUser event, so nothing happens further.
Again, if javascript is enabled in browser, all this works fine. Server receives this call and returns user's data.
How do i make server receive this event, return user's data and render it before sending to client?
As alternative, may be there is different way to make it SEO friendly?
React's componentDidMount lifecycle hook is not called server-side, as stated in the docs.
If you need to fetch data and use it server-side in the render method of a component, you need to pass this data as props during the initial render. This means, you cannot fetch it either during componentWillMount, even if the hook is called.
To achieve what you want, you need your server-side code to:
determine what components will be rendered
dispatch the proper actions so that your store will be properly populated
render your components only then - as the data is available to pass to your components in an initial render
The details on how to achieve that would of course depend on your flux implementation, the framework you use server-side, etc.

React isomorphic - issue with simultaneous client / server actions

I'm trying to build my app with React and Node (Isomorphic Rendering Architecture). I found on github example project but i have problem. I would like to develop my project client and server together, that the same Component can gets data/actions whataever from client nad server simultaneously. For example:
var Component = React.createClass({
render: function() {
return (
<div className="commentBox">
{this.props.client}
{this.props.server}
</div>
);
}
});
You can see that, Component gets props from client and server together. How i can do this?
I tryed 3 github projects but always i can't implement it. I dont know why. of course it's working when i render Component only by server or only by client but it's not working together.
For example when I render Component by server i can't make any actions specific for client (onclick alerting etc.) . So that's why it's important for me. Rendering some data from server and makes some client actions. But together, still on the same Component.
I'm sorry for my poor english!
Jan, it's impossible to do this using React.
They don't work "at the same time".
The server-side React code works by building the HTML page as a text-string, and serving the HTML text to the client.
After the browser loads the page, the React code in the browser will attach itself to the React code that was put on the page (because the server prints out IDs for all of the components, for the browser to attach to, after).
The goal, then, is to feed data to components, instead of expecting to have access to both the browser and the server at the same time.
That way, you can use server-side code to get data for the component, and you can use client-side code to get data for the component, and the component won't care.
This is not quite valid React, or the right way to do JS, in general but have a look:
class ServerElement {
render ( ) {
// sync calls should rarely ever (ideally never, other than booting up) be used
var articles = db.syncGetArticles();
return <Articles articles={ articles } />;
}
}
class BrowserElement {
render ( ) {
// isn't real, and should never be used even if it was
var articles = ajax.sync("GET", "/articles");
return <Articles articles={ articles } />;
}
}
The important part here is not the Server or Browser element (like I said, that's not really going to work), but rather that the <Articles /> element isn't expecting a server or a browser; it's expecting a list of articles.
The benefit of this approach, then, is that the server builds the HTML, but before the page is served, it's pre-filled with data, which will later be updated (replaced or added to) on the browser.
I hope that helps; if it doesn't, ask away, and I'll try to add to the answer.
#Norguard Thank you for your comprehensive answer. I am trying to own your answer. I know that your example code is not valid for React/JS cuz we have to build our db actions in models area. But one thing puzzles me. We are sending API with our '/articles' and gets data from this. OK, its cool, but this is still public data. I wonder about the private data. How to use React Isomorphic to get specific data or server if/else condition to build better app.
If we are using client-side templating language (like ejs) it's very easy. We are building our .html file and injection server methods(or whatever) to specific tags for templating language. How do to the same in React server? I can't imagines this using components and server.
I think that I understand idea you showed me but need time to efficiently build Isomorphic app using React.

React Node API Request Design Pattern

I need to make an API request to an external API using an API Key. I know how to make this API request in React by writing a onSubmit function. But since I have an API key that I want to keep a secret I am going to write a simple Node app to house env variables.
Besides messing around in node this is my first production experience with Node and I am wondering if my thought process is correct and if not, the better way to do this.
Most of this question will be pseudo code since I haven't started with the Node portion yet.
The idea is that from within the React component it would call the Node app who in turn would call the external API.
React -> Node -> External API
So the React component would be something like so:
handleSubmit: function() {
var data = this.refs.testData.getDomNode().value;
$.ajax({
url: '/my-node-endpoint',
dataType: 'json',
type: 'POST',
data: { test: data },
success: function(data) {
// Whatever success call I want to make
}.bind(this)
})
}
And then in my Node app it would like something like this:
app.post('/my-node-endpoint', function(req, res) {
// Store the values we are posting as JSON
// Start the post request
// On End tell the React component everything is ok
// Prosper
});
As always, thanks for any help that is offered.
Your thought process looks right to me.
If the API you are calling is from a different domain, you will have to build a wrapper on your node server like you did here. Unless the external API supports cross-origin requests with no domain restrictions (such as MapBox web services), you will have to do this.
Several improvements to your code:
As far as I know, you can use React.findDOMNode(this.refs.testData).value instead of this.refs.testData.getDomNode().value. getDomNode() is deprecated in v0.13.
For all the AJAX calls, you can use the Store concept in Flux. The store keeps the states of the data, including updating data through AJAX request. In your React UI code, you just need to call the methods of the store, which makes your UI code clean. I usually create a store class myself without using Flux.

nodejs mobile development: how control navigation flow

I am a nodejs newbie and would like to understand the navigation flow when using nodejs to serve mobile applications.
Moible app
index.html
Show all users
Nodejs server snippit
var myData = {
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
};
res.send(myData);
Question: how do I display this data on another page (users.html)? I've worked with nodejs where I can just render to a specific path and it picks the appropriate Jade file but not sure how to do it since the html / js files are on the phone and not the server.
If you know of an example application I can just look through that code and figure it out.
Thanks for your help.
First of all you need to understand that your node.js is executed on server side, and all it can do - response on requests and do some logic, that stays on the server.
Then there is .html and .js that is sent to your clients (browser), and it is rendered and executed on client-side. This execution and logic is very different, and is focused to provide user interactions and render all sorts of data.
So all you need is be able to 'ask' server for data (request) and then get response, validate it in browser, if it is valid, you can render it using JS.
In order to make your life easier, consider using jQuery.
AJAX - to make requests to server and get response with data.
express.js - web framework for node, helps with routes.
And just generally - go and try things, experiment and it is better to understand whole picture or specific details frist, before you making any decisions.

Resources