Get current member data and submit in the collection

Hi everyone.

Have issues with updating a collection with a code. Seen similar topics on this problem but did not find an answer.

Here is the scenario: the user goes to the page and fills a form. Need to fetch user’s email and nickname from PublicData and submit in the collection with the form data.

I have a problem and cannot solve it: required data is shown in the text input field, but it is not submitted to the collection when the button is pressed. PLease advise what do I do wrong.

Here is the code:


import wixUsers from 'wix-users';
import wixData from 'wix-data';

let user = wixUsers.currentUser;
let userId = user.id;   

 user.getEmail()
    .then( (email) => {
 let userEmail = email;
        wixData.query("Members/PublicData")
            .eq("_id", userId)
            .find()
            .then((results) => {
                console.log(results)
 let items = results.items;
 let lN = items[0].nickname;
 //following data is not saved
               $w('#input6').value = lN;             
               $w('#input8').value = userEmail;
            });
 });
            
$w.onReady( function ()
{     
     $w("#dynamicDataset").onReady(() => { 
        let itemObj = $w("#dynamicDataset").getCurrentItem(); 
                $w('#input5').value = itemObj.title;
                $w('#input7').value = userId;
       });
       });

And a screenshot of the page:

  1. Прежде всего, вы не говорите, каую … вы используете! (custom/wix-forms)
  2. Во-вторых, если вы ищете NICKNAME текущего пользователя, вам даже не нужно выполнять поиск в базе данных, зачем?
  3. В-третьих, вы должны полностью пересмотреть ваш код, так как он содержит много ошибок.

Если вы используете wix-формы, ввод данных —> вам будет непросто. Так что взгляните на этот пост здесь…

Похожая проблема описана в этом посте…

And now one more time for everybody…

Your code has a lot of ERRORs and wrong placed code-sections. It is not clear if you use a DATASET or WixData. Mixing-up both → in most cases will just end in → chaotic code, or even in a dead-end. But perhaps in your situation it is inevitable to use a mix of both, since you are dealing with → DYNAMIC-DATASETS.

You also do not mention, which kind of Form you are using?

  1. Custom one?
  2. Wix-Forms?

Also you are using the depricated and old → Wix-Users - >API, which was already replaced by a newer one called → Wix-Members.

Here you will find informations about how to deal with the new API…
https://www.wix.com/velo/forum/coding-with-velo/wixmember-not-working-after-initial-login-until-refresh

Your code will start with the IMPORTS followed by the onReady-Code-Part (with some exceptionel declarations between the two…

Try to use this one instead → it is not complete and also may not work 100% (i am not here to code for you) → BUT → It should give you the right direction!

import wixMembers from 'wix-members';
import wixData from 'wix-data';

$w.onReady(async()=>{
    let currentMember = wixMembers.currentMember; console.log("текущий член😂: ", currentMember);
    let member = await currentMember.getMember(); console.log("член😂: ", member);
    let loginEmail = member.loginEmail; console.log("логин-mail: ", loginEmail);
    let memberID = member._id; console.log("ID пользователя: ", memberID);
    let nickname = member.profile.nickname; console.log("Nickname: ", nickname);
  
    $w("#dynamicDataset").onReady(() => { 
        let item = $w("#dynamicDataset").getCurrentItem(); console.log("Current-Item: ", item); 
        $w('#input5').value = item.title;
        $w('#input7').value = userID;
        $w('#input6').value = nickname;             
        $w('#input8').value = loginEmail;
    });

    $w('#btnSubmit').onClick(()=>{//<---Submit-Button which will start the SUBMISSION!
        start_SubmissionWixData();
        //start_SubmissionDataset(); <-- do not pay attention on this..
        //...here i just wanted to create an alternative way ---> but was too lazy 😀😅
    }); 
});


 function start_SubmissionWixData() {
    wixData.query("xxxxxxDATABASExxxxx")
    .eq("xxxxDB-FIELDxxxx", "xxxxVALUExxxx")
    .find()
    .then((res)=> {console.log("результаты: ", res);
        let items = res.items[0];

        items.title = $w('#input5').value;
        items._id = $w('#input7').value;        
        items.nickname = $w('#input6').value;
        items.email = $w('#input8').value;

        wixData.save("xxxxDATABASExxx", items).then(()=>{
            console.log("Data saved!")
        })
    });
}

Good luck!
Удачи!

BTW: —> DO NOT FORGET TO TAKE A LOOK INTO —> CONSOLE !!! (And do your testings on a published site, for example using a google-chrome browser, with an already loged-in-USER)!

Большое спасибо за развернутый ответ, изучаю.
Thanks a lot for a profound answer.

https://www.wix.com/velo/forum/coding-with-velo/get-current-user-email-and-add-to-collection