Hi, I'm an jQuery/Angular Developer last 5 years, and now I've planned move to ReactJS. I'm learning ReactJS by my own, as comparing the similar stuff what I did in jQuery (or Angular). My plan is, just to make a Login-Logout App, with ReactJS front-end and CodeIgniter - MySQL are the backend and database, respectively. Also I know what is CORS, and I'm pretty clear about the REST concepts. Let me explain my react app in brief.

My App component, calls an API via fetch, and upon the response which tells either session is set (as user is logged in) or session isn't set (user logged out/session expired), then the component will render either the 'Login Panel' component or a 'Dashboard' component. It works fine, as I tested. This is my App component.

class App extends Component {
    constructor(props) {
        super(props); //compulsary
        this.state = { isUserAuthenticated: false };
    }
    componentDidMount() {
        var innerThis=this;
        fetch('http://localhost/forReact/index.php/general/authenticate',{
          method:'GET',
          Content_type:'application/json',
          headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
          mode: 'cors',
          cache: 'no-cache'})
        .then(res => { return res.json() })
        .then(data => { alert(data.message); this.setState({isUserAuthenticated:data.result}); })
        .catch(err => console.error(err));
        }
        render() {
            return (this.state.isUserAuthenticated?<Home/>:<First/>);
        }
    }
    export default App;

This is my CodeIgniter Controller's relevant method (the controller name is General.php)

public function authenticate(){
$session_data = $this->session->get_userdata();
if (is_null($session_data)) {
$this->sendJson(array("message"=>"No session","result"=>false));
}
else if (empty($session_data['username'])) {
$this->sendJson(array("message"=>"No username index","result"=>false));
}
else if ($session_data['username']=="") {
$this->sendJson(array("message"=>"Empty Username","result"=>false));
}
else{
$this->sendJson(array("message"=>"Valid Session","result"=>true));
}
}

This is the login component, which is being rendered in the App component, when there are no sessions set.

class LoginPanel extends React.Component {
  constructor(props) {
    super(props); //compulsary
    this.unRef = React.createRef();
    this.pwRef = React.createRef();
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(){
  var toServer={"userName":this.unRef.current.value,"passWord":this.pwRef.current.value};
        fetch('http://localhost/forReact/index.php/general/login',{
          method:'POST',
          Content_type:'application/json',
          headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
          body: JSON.stringify(toServer),
          mode: 'cors',
          cache: 'no-cache'})
        .then(res => { return res.json() })
        .then(data => { alert(data.message); })
        .catch(err => console.log(err));
  }

  render() {
   return (
     <form onSubmit={this.handleSubmit}>
     <input ref={this.unRef} type="text" className="form-control" placeholder="Username"/>
    <input ref={this.pwRef} type="password" placeholder="Password"/>
    <button style={{margin:'1%'}} type="submit">Login</button>
    <button style={{margin:'1%'}} type="reset">Help</button>
     </form>);
   }
 }
export default LoginPanel;

Finally, this is the CodeIgniter Controller's relevant method (the same controller General.php)

public function login(){
$arrived = json_decode(file_get_contents('php://input'), true);
if (!empty($arrived['userName'])&&!empty($arrived['passWord'])) {
$fromDB=$this->Mdl_general->login($arrived['userName'],$arrived['passWord']);
if ($fromDB['result']) {
$this->session->set_userdata('username',$arrived['userName']);
$this->sendJson(array("message"=>$fromDB['message'],"result"=>$fromDB['result']));
}
else{
$this->sendJson(array("message"=>"Username and or Password is/are incorrect!","result"=>false));
}
}
else{
$this->sendJson(array("message"=>"Invalid or Missing Input Parameters!","result"=>false));
}
}

My issue is, when I logged in with the correct username and password (what I have in the mysql table, the alert message is successfully showing, however, it seems the session is not set by the php code,

$this->session->set_userdata('username',$arrived['userName']);

However, if I did the above 'set session' code via a separate controller function, it sets the session successfully. However, even after that, the App component's API Call, still getting the response as the session is not yet set.

What might be the reason? I tried the same via jQuery's Ajax Call and it works. I knew the fetch is much more different from the Ajax Call of jQuery. Could anyone explain, why this login component, didn't trig the PHP code to set the session?

Because React does not carry out a page refresh the cookie storage that React has access to is outdated.

The best method for React & PHP authentication is to use token authentication:
Click Here

I have no react experience, but I do have CI experience.

Are you including the session library, and not closing the session before using set_userdata()?

I use CI 3 with MySQL, and, per this page, I ran into issues with my until I started using session_write_close() near the top of the script. However, that means I can't use set_userdata further down in the script.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.