easy pass data from express to react - reactjs

So I'm trying to learn ReactJS but the documentation is terrible, after reading it I am even more confused than before.
I will keep it simple for the sake of learning:
This is my old approach:
Current:
app.use(function (req, res, next) {
res.locals.user = req.user || null;
next();
});
So I get it with {user} in handlebars.
Now for react:
{this.props.user}
returns NULL. Seriously, what the ...? How to pass the variable easily?

ReactJS is mostly used for single page applications, meaning that most data is fetched after the application is loaded. If you want to use ReactJS as a template engine with expressJS use express-react-views. Otherwise you need to prerender ReactJS with react-prerender when using NodeJS.
But I guess what you really want to do is to read/watch a good ReactJS tutorial.
Here are some resources for you:
Learn React & Redux
Simple React Development in 2017
Hope that brings you on track :)

Related

In separation of the front and back ends of Rails + React, how to find API endpoints and React routes?

I took over a separate front-end and back-end website, consisting of two back-ends, Ruby on Rails and React. Prior to this, I have always used the MVC framework to make websites, but now the "V" part has become a React repo independently.
Specifically, I have to write a render json: #variable in a Controller#Action, but after this I don't know where the json is transmitted to the front end (React repo)? I don't know how to find the API endpoint.
I heard that this is related to React route? What's this? Where is this written?
The problem is very big, please let me know if you have any recommended teaching articles.
If you are making Rails as backend and React as frontend you need to call Rails API from React. You need to return json from Rails method, you can declare format also in method so if format type is json return as json else return html.You can check confi/routes to know path for method.
To check if rails API call is working and how data is getting return you can use postman. Once tested in postman same api with http method (get,put, post etc) and parameter can be passed as API in React.
example
Blockquote
loadTdlists() {
axios
.get("users/user_list.json")
.then((res) => {
this.setState({ tdlists: res.data });
})
.catch((error) => console.log(error));
}
Blockquote
here user_list method is define in users controller. you can use full URL also when calling api according to project requirement.
I'm a beginner in rails, I started project rails api + react.native on front. Where I find my endpoints to frontend was in one command.
rails routes
which show us some data like:
new_api_user_session GET /api/v1/auth/sign_in(.:format) devise_token_auth/sessions#new
api_user_session POST /api/v1/auth/sign_in(.:format) devise_token_auth/sessions#create
destroy_api_user_session DELETE /api/v1/auth/sign_out(.:format) devise_token_auth/sessions#destroy
new_api_user_password GET /api/v1/auth/password/new(.:format) devise_token_auth/passwords#new
edit_api_user_password GET /api/v1/auth/password/edit(.:format) devise_token_auth/passwords#edit
api_user_password PATCH /api/v1/auth/password(.:format) devise_token_auth/passwords#update
PUT /api/v1/auth/password(.:format) devise_token_auth/passwords#update
POST /api/v1/auth/password(.:format) devise_token_auth/passwords#create
cancel_api_user_registration GET /api/v1/auth/cancel(.:format) devise_token_auth/registrations#cancel
new_api_user_registration GET /api/v1/auth/sign_up(.:format) devise_token_auth/registrations#new
edit_api_user_registration GET /api/v1/auth/edit(.:format) devise_token_auth/registrations#edit
api_user_registration PATCH /api/v1/auth(.:format) devise_token_auth/registrations#update
PUT /api/v1/auth(.:format) devise_token_auth/registrations#update
DELETE /api/v1/auth(.:format) devise_token_auth/registrations#destroy
POST /api/v1/auth(.:format) devise_token_auth/registrations#create
new_api_user_confirmation GET /api/v1/auth/confirmation/new(.:format) devise_token_auth/confirmations#new
api_user_confirmation GET /api/v1/auth/confirmation(.:format) devise_token_auth/confirmations#show
POST /api/v1/auth/confirmation(.:format) devise_token_auth/confirmations#create
api_v1_auth_validate_token GET /api/v1/auth/validate_token(.:format) devise_token_auth/token_validations#validate_token
for example /api/v1/auth/sign_in is endpoint to register a user. I gave it to frontend developer and works well. If you want to test your endpoints you can use program like Insomnia or Postman with json data in it.

How to route for a react-router app using express?

So I have a backend running in expressjs and I have multiple routes on it. Now I just followed this tutorial to set up a RESTful api on express. Now I want to switch to full react on the frontend, so that I will have an api running in the backend to get things from the database and am thinking using fetch from react to get that data. I saw many people say that is the best way to do it. But now there is an issue, I am not sure how to route for this. I have react-router setup so I am assuming I would use that. But how can I serve these files to the client side? How can I make sure every route except /api routes just serve my js files? Like I have a built folder already with an index.html and main<hash>.js. I am running them easily but how can I intergrate them with express? I was not able to find any answers to this. How can I route for a reactjs app to be served using expressjs? and also I saw a tutorial telling me to use a * route but that means even my api routes will only point to that.
There are three ways basically to render an application.
One is Server Side Rendering, the other one is Client Side rendering and the third one is Isomorphic rendering.
So if you are defining your routes in Nodejs and navigating the application through those routes than it will be entirely server side rendering.
I saw a tutorial telling me to use a * route but that means even my
api routes will only point to that. ? How can I make sure every route
except /api routes just serve my js files?
Regarding this what you can do is
server.get('/api', (req, res, next) => {
//You can handle the request here
})
server.get('*', (req, res, next) => {
//You can handle the request here
})
You can define your route in this order.So by this way any call to the '/api' will be handled by the first route and all the other request will be handled by the second route.
Now I want to switch to full react on the frontend, so that I will
have an api running in the backend to get things from the database and
am thinking using fetch from react to get that data
Here you dont need this.It will be an client side rendering completely
server.get('*', (req, res, next) => {
//You can handle the request here
})
For this you can create an react app from scratch or use some boilerplate (https://github.com/facebookincubator/create-react-app).
There you can define all the routing and simply call the url http://localhost/api/xxxx and get the data and you can use this data in the frontend.In this case there will be a Nodejs Server which will be serving the frontend and the expressjs server will he hosting the 'api' service to get data from.
I have react-router setup so I am assuming I would use that. But how
can I serve these files to the client side?`
How can I route for a reactjs app to be served using expressjs?
The Reactjs app when compiled is a combination of static files comprising mainly of html, css, javascript. If you want your app to be served by your express.js server then you need to use isomorphic rendering. It is by far the best approach for rendering application as it is good for SEO and initial fast page load. It comes at the cost of a complicated setup. In this case, whenever the page refreshes or the first request comes, express will serve the first page (index.html) and index.html will contain the required static(bundled) js and css files for client side rendering. The first rendering will be done by the express server and the subsequent rendering will be done by browser itself.

Handle redirects with OAuth 2.0?

What is a good way to handle redirects in React Native with OAuth? There are external APIs I need to call, so I’ve registered my app, but I’m unclear what the redirect URI should be. For a web app, it would make sense how to handle this, but I’m not sure with React Native.
What you need to do in React Native is setup your application for deep linking. A deep link is a way for another application or in this case your browser/WebView to say "Hey! I'd like to pass this information back to a native app".
Setup:
Setup a url scheme in Xcode. This will allow you to redirect to url's formatted something like this myApp://oauthLogin
Setup Linking
From there you should be able to create an event listener for the Redirect URI that you pass to the oauth service, in this case your deep link.
componentDidMount() {
Linking.addEventListener('url', (url) => {
console.log(url);
// => myApp://oauthLogin?authCode=abc123
});
}
You will have to add extra code the make sure the url is in the correct format but i hope that gets you closer!

AngularFire2 vs Firebase JS

I'm finding the AngularFire2 library to be poorly documented and very hard to use. I have an angular2 app and was wondering if someone could help me clear up the pros/cons of just using the vanilla JS Firebase code rather than angularfire2? Does using the vanilla JS version kill off angular2 functionality that I may be using? I'm confused as to why use one over the other, personally the vanilla JS one is waaaay better documented and feature rich, I can't even see how to Signup Users in AngularFire2, it doesn't have any UI elements and observables are doing my head in!
You can use vanilla version directly. Even with observables - observable and promises work well together. For example:
Observable.of(new firebase.auth.GoogleAuthProvider())
.switchMap(o => firebase.app().auth().signInWithPopup(o))
.subscribe()
Main advantage of AngularFire2 are head-hurting observables (; I suggest you learn rxjs and start using them over promises. I am using vanilla JS SDK, however, I've created refObservable based on what AngularFire2 does with FirebaseObservables. It's simpler, but enough for my needs:
export function refObservable(ref): Observable<firebase.database.DataSnapshot> {
return Observable.create(observer => {
let fn;
try {
fn = ref.on('value', snapshot => {
observer.next(unwrapSnapshot(snapshot));
});
} catch (error) {
observer.error(error);
}
return () => ref.off('value', fn);
});
};
where unwrapSnapshot(snapshot) is simple function that checks snapshot and returns appropriate result (array, object, string, etc...). I use it for reading data from firebase. Create/Update/Delete operations I do directly:
Observable.of(checkUserPermission())
.switchMap(() => {
return firebase.database().ref('what/ever').remove();
});
It's similar with other modules - storage, messaging, auth... I prefer Firebase SDK over AngularFire2. I also find it easier to use in service/web workers.
If you already know vanilla sdk, stick with it.
If you only need database read/write and basic authentication use AngularFire2 it's simpler.
If you need more control over firebase features use JS SDK.

ReactJS Add local path

I am just starting with ReactJS and trying to integrate with Stormpath for user login. They provide default behaviors for /register and /login path.
I want ReactJS to redirect to those local links for now rather than creating new routes and components. How can this be achieved.
Thanks!
I also work at Stormpath and just a few days ago I released the Stormpath React SDK. With this you'll be able to integrate Stormpath into your React application with very little effort.
To get started checkout our example application or read the blog post I wrote for it.
And if you have any questions, feel free to hit me up at robin [at] stormpath [dot] com.
Cheers!
I work at Stormpath. We're recommending that you try to use our express-stormpath module. But we do have some issues that we're working on fixing.
It is not yet possible to disable the default HTML views, but still retain the JSON API. We will be fixing this in a future release. This creates a problem for React Flux applications that want to use the /login route in their browser application, but not use our default HTML views.
To work around the problem, you can change the uri of the route to a different URL than /login. For example:
app.use(stormpath.init(app, {
website: true,
web: {
login: {
uri: '/api/login'
}
}
}));
Your browser code will need to make it’s login POST to /api/login
Can you give this a try and let me know if is helps? Thanks!

Resources