1

I succesfully change the menu state, with hooks but...

  const [menu, setMenu] = useState([
    {
      parent: 'User',
      permission: false,
      children:[
        {name: 'Vendor', permission: false, readonly: true},
        {name: 'Client', permission: false, readonly: true},
        {name: 'User', permission: false, readonly: true},
      ]
    }
  ]);

  const toggleParent = (key) => {
    let data = {...menu};
    data[key].permission = !data[key].permission
    setMenu(data);
  };

end up getting error in mapping function, it says:

menu.map is not a function

here is the mapping function:

                  {menu.map((value, key) => (
                    <Switch
                      checked={value.permission}
                      onChange={() => toggleParent(key)}
                      color="primary"
                      name="checkedB"
                      inputProps={{ 'aria-label': 'primary checkbox' }}
                    />
                  ))}

2 Answers 2

2

I think the issue is coming from {...menu}. Usually this error happens when you call .map() not on an array. You need to have an [] instead.

Try the following:

const toggleParent = (key) => {
    let data = [...menu];
    data[key].permission = !data[key].permission;
    setMenu(data);
};

I hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1

There is a problem in your code, Your menu is an array and your are assigning it an object and using a map over it.

Here is the correct way of doing this.

const toggleParent = (key) => {
    let data = [...menu];
    data[key].permission = !data[key].permission
    setMenu(data);
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.