Reputation: 4496
I currently have an Express backend that serves up a Login page to users, which is part of a React App. There's a button on the page of the app that routes users through Google's O-Auth process, eventually returning the user information, like this:
router.get("/google/redirect", passport.authenticate('google'), (req,res) => { // Returns user information from google...
res.redirect("/dashboard");
// req.user <–– My user information is here...
});
In the main server.js
file of my application, I have an app.get
route waiting below the middleware for my authentication ready to serve up my React.js compiled index, here:
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, "index.html"));
});
That GET route serves my React.js file, which contains "public" and "private" routes based on my Redux state. The React file (before it's compiled into my index.html/javascript bundle being served by the above route) looks like this before it's compiled:
const store = configureStore();
const jsx = (
<Provider store={store}>
<AppRouter />
</Provider>
);
const renderApp = () => {
ReactDOM.render(jsx, document.getElementById('app'));
hasRendered = true;
};
renderApp();
What I'd like to be able to do, is somehow 'send' the data from my Express backend to my Redux state. That way, when user logs in, the Redux "isAuthenticated" state changes, and then when I'm routed to the private "/dashboard" route.
How could I send this MongoDB data to my Redux store and then reroute the user to the appropriate page (\dashboard
)? Or is there a better way of rendering the initial React state, so that I can display a Login screen, and then once the user logs in, redirect them and change the Redux state from information from the backend?
Upvotes: 1
Views: 5331
Reputation: 525
I see that your main question how you can retrieve data from MongoDB to React and then change the state.
It will be done like any other request from Client --> Server.
Now how you can request data from Mongodb depends on its implementation :
If you are running MongoDb as a node package such as Mongoose, then you would make a call from React --> Express Server which will serve the data from database.
The request from React --> Express will look something like this :
React Code :
callAPI(){
fetch("http://localhost:9000/testAPI")
.then(res=>res.text())
.then(res=> this.setState({apiResponse :res}))
.catch(err=> err);
}
componentDidMount(){
//this can be any event. This is just an example
this.callAPI();
}
And then Express must server route /testAPI with the data that you are looking for.
Express testAPI.js
express = require('express');
router = express.Router();
router.get('/', function(req,res, next) {
res.send('API is working perfectly.');
});
module.exports = router;
Let me know if this answers your question.
Upvotes: 2