Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current logged in user in react js

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.

like image 271
Ed Lynch Avatar asked Sep 02 '25 02:09

Ed Lynch


1 Answers

First of all you need to use a method for authentication, JWT is a good bet to do so. then in your main component (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 components 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.

like image 109
Shahin Ghasemi Avatar answered Sep 04 '25 17:09

Shahin Ghasemi