Guest User

Untitled

a guest
May 25th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import wixUsers from 'wix-users';
  2.  
  3. import wixData from 'wix-data';
  4.  
  5. import wixLocation from 'wix-location';
  6.  
  7.  
  8.  
  9. $w.onReady( () => {
  10.  
  11. if(wixUsers.currentUser.loggedIn) {
  12.  
  13. $w("#loginButton").label = "Logout";
  14.  
  15. $w("#profileButton").show();
  16.  
  17. }
  18.  
  19. else {
  20.  
  21. $w("#loginButton").label = "Login";
  22.  
  23. $w("#profileButton").hide();
  24.  
  25. }
  26.  
  27. } );
  28.  
  29.  
  30.  
  31. export function
  32. loginButton_click(event) {
  33.  
  34. // user is logged in
  35.  
  36. if(wixUsers.currentUser.loggedIn) {
  37.  
  38. // log the user out
  39.  
  40. wixUsers.logout()
  41.  
  42. .then( () => {
  43.  
  44. // update buttons
  45. accordingly
  46.  
  47. $w("#loginButton").label = "Login";
  48.  
  49.  
  50. $w("#profileButton").hide();
  51.  
  52. } );
  53.  
  54. }
  55.  
  56. // user is logged out
  57.  
  58. else {
  59.  
  60. let userId;
  61.  
  62. let userEmail;
  63.  
  64.  
  65.  
  66. // prompt the user to log in
  67.  
  68. wixUsers.promptLogin( {"mode": "login"} )
  69.  
  70. .then( (user) => {
  71.  
  72. userId = user.id;
  73.  
  74. return user.getEmail();
  75.  
  76. } )
  77.  
  78. .then( (email) => {
  79.  
  80. // check if there is an item for the user in the collection
  81.  
  82. userEmail = email;
  83.  
  84. return wixData.query("profile")
  85.  
  86. .eq("_id", userId)
  87.  
  88. .find();
  89.  
  90. } )
  91.  
  92. .then( (results) => {
  93.  
  94. // if an item for the user is not found
  95.  
  96. if (results.items.length === 0) {
  97.  
  98. // create an item
  99.  
  100. const toInsert = {
  101.  
  102. "_id": userId,
  103.  
  104. "email": userEmail
  105.  
  106. };
  107.  
  108. // add the item to the collection
  109.  
  110.  
  111. wixData.insert("profile", toInsert)
  112.  
  113. .catch( (err) => {
  114.  
  115. console.log(err);
  116.  
  117. } );
  118.  
  119. }
  120.  
  121. // update buttons accordingly
  122.  
  123. $w("#loginButton").label = "Logout";
  124.  
  125.  
  126. $w("#profileButton").show();
  127.  
  128. } )
  129.  
  130. .catch( (err) => {
  131.  
  132. console.log(err);
  133.  
  134. } );
  135.  
  136. }
  137.  
  138. }
  139.  
  140.  
  141.  
  142. export function
  143. profileButton_click() {
  144.  
  145.  
  146. wixLocation.to(`/profile/${wixUsers.currentUser.id}`);
  147.  
  148. }
Add Comment
Please, Sign In to add comment