1

I am building a web application that can store and retrieve user data. Once I add A User i increment count by 1. Once incremented the users data is added and I can fetch the data by the fetchUser(count - 1) function. Is there a way to connect this id to the users Address so that the id can be fetched when a user signs in.


    mapping (uint => Users) public users;
    mapping(address => bool) _isRegistered;

    constructor() public {
        owner = msg.sender;
        userCount = 0;
    }

function addUser(string memory _name, bool _isReg) contractIsActive() public returns (bool){
        require(!_isRegistered[msg.sender], "sender is already registered");
        emit LogUser(userCount);
        emit LogAddressUser(msg.sender);
        users[userCount] = Users({name: _name, userId: userCount, signedUp: _isReg});
        _isRegistered[msg.sender] = true;
        userCount += 1;
        return true;
    }

function fetchUser(uint _id) public view returns(string memory name, uint id, bool signed){
        name = users[_id].name;
        id = users[_id].userId;
        signed = users[_id].signedUp;

        return(name, id, signed);
    }
1
  • I didn't understand your question. You should have provided more information
    – zmy
    Aug 9 at 2:13
1

Yes, you can create a mapping which connects each address to its id (check the comments):

    mapping (uint => Users) public users;
    mapping(address => bool) _isRegistered;
    mapping(address => uint) public userId; // Here is the mapping

    constructor() public {
        owner = msg.sender;
        userCount = 0;
    }

function addUser(string memory _name, bool _isReg) contractIsActive() public returns (bool){
        require(!_isRegistered[msg.sender], "sender is already registered");
        emit LogUser(userCount);
        emit LogAddressUser(msg.sender);
        users[userCount] = Users({name: _name, userId: userCount, signedUp: _isReg});
        _isRegistered[msg.sender] = true;
        
        userId[msg.sender] = userCount; // We register it here

        userCount += 1;
        return true;
    }

function fetchUser(uint _id) public view returns(string memory name, uint id, bool signed){
        name = users[_id].name;
        id = users[_id].userId;
        signed = users[_id].signedUp;

        return(name, id, signed);
    }

// We can now retrieve an id using the address:
function fetchUserId(address _userAddress) public view returns(uint id){
    return userId[_userAddress];
    }

Beware thought that in this implementation an inexistent user will return an id of 0. You may change this behavior depending on your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.