Skip to content

Instantly share code, notes, and snippets.

@kayode-adechinan
Created March 6, 2020 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kayode-adechinan/af2324c4c09e553b3cf96f6268ddd5cb to your computer and use it in GitHub Desktop.
Save kayode-adechinan/af2324c4c09e553b3cf96f6268ddd5cb to your computer and use it in GitHub Desktop.
// login.jsx
import React, { Component } from "react";
import cookie from 'js-cookie'
import Router from 'next/router'
export default class Login extends Component {
login = () => {
cookie.set('status', "logged", { expires: 1 })
Router.push('/profile')
};
render() {
return (
<div>
Click to log in
<button onClick={this.login}>Login</button>
</div>
);
}
}
import React, { Component } from "react";
import cookie from 'js-cookie'
import Router from 'next/router'
import nextCookie from 'next-cookies'
export default class Profile extends Component {
static async getInitialProps(ctx) {
const { status } = nextCookie(ctx)
console.log(status)
if (ctx.req && !status) {
ctx.res.writeHead(302, { Location: '/login' })
ctx.res.end()
return
}
return {status}
}
logout = () => {
cookie.remove("status");
Router.push('/login')
};
render() {
return (
<div>
Welcome deny
<button onClick={this.logout}>Logout</button>
</div>
);
}
}
@kayode-adechinan
Copy link
Author

kayode-adechinan commented Mar 6, 2020

import React, { Component } from "react";

import cookie from "js-cookie";
import Router from "next/router";
import nextCookie from "next-cookies";

class Profile extends Component {


  render() {
    return (
      <div>
        Welcome deny
        <button onClick={this.props.logout}>Logout</button>
      </div>
    );
  }
}

const withAuthSync = WrappedComponent => {
  return class withAuthSync extends Component {
    static async getInitialProps(ctx) {
      const { status } = nextCookie(ctx);
      console.log(status);

      if (ctx.req && !status) {
        ctx.res.writeHead(302, { Location: "/login" });
        ctx.res.end();
        return;
      }

      return { status };
    }

    logout = () => {
      cookie.remove("status");
      Router.push("/login");
    };

    render() {
      return <WrappedComponent logout={this.logout} />;
    }
  };
};



export default withAuthSync(Profile)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment