skip to Main Content

When I call my permissionCheck it doesn’t return true or false.
The permissions useState is full.

This is the part of my code:

const [permissions, setPermissions] = useState({});

const permissionCheck = (permission) =>
    {
        var i;
        for (i = 0; i < permissions.length; i++)
        {
            if (permissions[i].name === permission)
            {
                return false;
            } else if (permissions[i].name !== permission) return true;
        }
    }


// the outcome will be set on the hidden component. So if the outcome is true it will be hidden and if it is false it will be shown
hidden={permissionCheck('TEST')}

2

Answers


  1. It is because you are not returning. If both conditions are not met.

    Change

    const permissionCheck = (permission) =>
        {
            var i;
            for (i = 0; i < permissions.length; i++)
            {
                if (permissions[i].name === permission)
                {
                    return false;
                } else if (permissions[i].name !== permission) return true;
            } 
          // 👈 There is no default return, so you are not getting any returned value
        }
    

    to

    const permissionCheck = (permission) =>
        {
            var i;
            for (i = 0; i < permissions.length; i++)
            {
                if (permissions[i].name === permission)
                    return false;
            }
            return true; // 👈 so now one return is assured.
        }
    
    Login or Signup to reply.
  2. You try to iterate through an object which does not work

    Change permissions from object

    const [permissions, setPermissions] = useState({});
    

    To array:

    const [permissions, setPermissions] = useState([]);
    

    And amend your function as follows:

    const permissionCheck = (permission) =>
    {
        var i;
        for (i = 0; i < permissions.length; i++)
        {
            if (permissions[i].name === permission)
            {
                return false;
            }
        }
       return true;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search