redux-react-session how to get user info into state on refresh - reactjs

I new to react. I am trying to do login for that i used redux-react-session package from npm to store sessions.
I am able to store session and autherise routes based on login.
But when i refresh page i want to restore user session into state.
As per document of redux-react-session we can user
sessionService.loadUser() method to get user back.
This function return promise in response.
But i am not able to get excat user object. Its returing user as a promise.
i have spend almost 10 hrs on it.
Can anyone help?

It is hard to understand what is going wrong with your code. Can you share it somehow?
Are you sure you call this line of code after store creation?
sessionService.initSessionService(store);
And finally you can implement such logic by yourself.
After login, put data to the localStorage. After store creation, get data from the localStorage and put it in your store. It is pretty easy logic.

Related

Saving user data in redux but not in localStroage

I have user data which includes Email,Username,Password,ShippingAddress etc..
I am storing jwt token in localStorage, the token is includes :username,id,createdAt..
I want the user data to be persisted to my redux-store but I can't figure out how to do it.
I don't want user info to be in local storage but on the other hand everytime I refresh the page my user data from redux getting deleted, I kinda stuck.
Tried to do simple check that if localstorage(jwt) id is equal to the user that just logged in - store the data in store and it works, but as I said one refresh delete all..
Would like to get some hints\tips from the pros! :)
Using: graphql\apollo, redux toolkit, react.
My best idea was to have requests from the server on every component that I need username \ email \ password ..etc but I think it will be too massy..
React is just JavaScript, and as such, any data that is stored in React will not persist and will be lost when the page is refreshed. Any information that you want to persist after a page refresh will need to be stored somewhere else (i.e. local storage).
There are ways to retrieve information from local storage and store them (non-permanently) in Redux after every page reload. How that solution looks will differ depending on how you are using React.
If you are using functional components and hooks, the useEffect hook can be used to retrieve data from localStorage after every page reload. Click here to read the docs on useEffect. It might look something like this:
useEffect(() => {
const storedData = JSON.parse(localStorage.getItem("storedData"));
// save to component's state or redux here.
}, []);
If that useEffect is placed somewhere in your app component, it will run on every re-render, thereby making it seem like the data is persisting in React because it will always be there.
Normally the flow that you would have should be smth like:
User logs in e.g /api/v1/login,
Sever returns either a temporal token (in case you are using otp codes or 2fa), or the user jwt that will be used for authorizing subsequent requests.
Token is saved in local storage.
When the user refreshes the page you check local storage and use the token on a request to the server (this way you can check it's still valid, normally you can do smth like /api/v1/user to get the user data.
If the token is valid then you can store the user info returned by the API call into the redux store. If not you can redirect user to login page again

How to manage a session in memory without using local/sessionStorage with React?

This is probably a duplicate question, but I'm struggling to find what I need. What I'm trying to achieve is a "session" that stays live until the user logs out. What I need to store in this session is username of logged user, and possibly isloggedIn boolean flag to use in my router. Previously, I was using sessionStorage while developing the app, but now that it's time for go-live I will need a more secure approach. My idea is to simulate sessionStorage but in memory. I need a session object that will hold the aforementioned information and will not reset its state on component re-render or whenever I manually change the URL route in the URL bar of the browser. I tried using static attributes in a method, but it looks like the import of the class in the application is reloaded every time the state of the static attributes is reset. I'm using axios as my HTTP client and JWT tokens as authentication for server requests, however I would like to use the session object to manage the routing of the app. I look forward to you replies. Thanks in advance.

Caching User after Authenticating with apollo

I'm quite new with react-apollo, however wasn't sure how to approach this problem. I'm authenticating a user with a mutation but would like to access that same user object, that's returned in other components again (live navbar, to render button options, or a profile button once logged in). Should I just fetch the current logged in user everytime I need it? I.e.
query GetUser {
id
name
role {
name
}
dob
}
Append this at the end of every component that needs it? I'm not sure if the best way might be to just cache it after logging in once versus this Even then how do you specifically cache it? I know inheritently it caches it as well, so its not like i have redundancy in fetching, however i might in code. What are some approaches y'all took.
in react applications to save user data for authentication you have to save user data in storage like local storage and store to your global state of your application like redux and mobx to access from all over the application.
i recommend to you using redux.
note:
every time when start application you have to store data from storage to global state again.
also you can use apollo-cache-persist but i don't tried this!

How to handle logged in status using React Router?

I'm a noob, starting my very first project with Node, Express, and React.
I got the authentication working, I have a Component that calls an action, which calls a store (or should), but this is where I get confused. I don't know where to go.
My LoginActions.login makes an api call to login the user, it comes back successfully and stores a cookie with the session ID. After that, how do I tell the UI to go to the dashboard? How do I make the UI KNOW that the user is actually authenticated, and if it's not, kick him out?
Where am I supposed to check for all that? Is it the store? The component itself?
Any help would be greatly appreciated.
You're not really "supposed" to do it in any specific way. React is more of a library than a framework. You can use it however you see fit.
One option would be to use react-router's onEnter function to verify logged in status and user it's replace method to redirect accordingly.
You could also have your components themselves verify logged in status and instead render your login form if not logged in yet.
Or you could even store your login form at a unique uri and handle all of the authentication via the server, using 302 redirects based on logged in status.
Up to you!

Reset User data loaded by auth component

I have auth component working greatly till I implemented a page for the user to change the user's info. I experienced some unknown results till I found out that after user's info being changed by that action, the user data loaded by auth component in session still remains the same. I wanted to know if there is any way to force auth component reload the user data from database again?
I considered re-logging in the user but it makes the logs complicated and places some bad traces in program. is there any more beautiful way to do so?
$this->Session->write('Auth', $this->User->read(null, $user_id));
you got to update it, cake does not do everything for you ;)

Resources