-1

Kind of a beginner with React so I have a question about users and how I can reuse the data after you are being signed in.

So in PHP I could check if you where signed in by running <?php if(isset($_SESSION['user']){}) ?>, what I wanna know is how this is done with React?

My backend is based on PHP sending JSON data back and forth. One of these requests is when you sign in. I currently store the data in localStorage but also want to display different data on some pages depending on signed in status, and I wanna display user data in the middle of the page like a Welcome back (user)!.

Whats the best method of doing this? Preferably without with whats built into Reactjs.

1 Answers1

1

I'm not sure why you'd prefer not to do this in the client as its not hard to achieve. In React, you'll need a method of managing application state. You could store logged in status in the Context API and that could be OK for a small application, a more complex one might use something like Redux (https://redux.js.org/introduction/getting-started)

If you use context you should see https://medium.freecodecamp.org/how-to-protect-your-routes-with-react-context-717670c4713a for example which discuses this.

You can also now use hooks to manage Context API and that'll be covered in the React docs (https://reactjs.org/docs/hooks-reference.html#usecontext)

Once you have the loggedInStatus ( for example as a state property) you can show different views in a number of ways like , conditionally using something like

<div>
{ 
  this.state.loggedIn &&
  <MyLoggedInView />
}
</div>

Or via routing for example Redirect user with router depending on logged in status.

I hope that gives you some ideas.

dorriz
  • 1,927
  • 3
  • 12
  • 19