just wondering how to access the data of a logged in authenticated user in a react js file with node js.
In the handlebar files I have I can see information like this:
{{#if user}}
I would like to know how to do things like that in a react js file so I can assign the name of the logged in user to a js variable. Something like
var name = {{# user.name }};
Thanks in advance and sorry if I've missed something out or said something a tad dense.
just wondering how to access the data of a logged in authenticated user in a react js file with node js.
In the handlebar files I have I can see information like this:
{{#if user}}
I would like to know how to do things like that in a react js file so I can assign the name of the logged in user to a js variable. Something like
var name = {{# user.name }};
Thanks in advance and sorry if I've missed something out or said something a tad dense.
Share Improve this question edited Jul 7, 2017 at 13:26 Neil Lunn 151k36 gold badges355 silver badges325 bronze badges asked May 29, 2017 at 18:16 Ed LynchEd Lynch 6234 gold badges10 silver badges28 bronze badges 3- 2 React isn't a full framework, so there's nothing built in for checking if a user exists or is logged in you have to build that yourself, or find a library that provides that. – Adam Commented May 29, 2017 at 18:36
- did you find any solution..? – Muhammad Usama Mashkoor Commented Sep 15, 2017 at 21:22
- Kinda, I added the users id to the page and got it by using a get elementById in the react code. – Ed Lynch Commented Sep 21, 2017 at 22:49
1 Answer
Reset to default 5First of all you need to use a method for authentication, JWT is a good bet to do so. then in your main ponent (app.js
) send a request to a specific route (like /auth/init
) to check if the user is logged (means jwt is set).
you can approach this using middlewares if you are using express.js
. if the user was logged in then send the user's credentials back to the client (react) and initialize your user
state with the response.
To share user state between your ponents you have different options. based on your needs you can choose from redux
, contextAPI
, or just newly introduced API hooks
. read this for further perspective.