skip to Main Content

I’m working on toggling checkboxes and I have two questions. I have a checkbox component and a parent component that is responsible for triggering the checkboxes. When I use the following code and pass it to my setCheckboxState it only allows me to select one checkbox at a time.

const selectCheckbox = (e: boolean, id: number) => {
  let updatedList = list.map((item) => {
    if (id === item.id) {
      return {
        ...item,
        isChecked: e,
      };
    }
    return item;
  });

  setCheckboxState(updatedList);

};

However, when I move the code inside of the setCheckboxState itself it works. Why doesn’t the first code snippet work?

const selectCheckbox = (e: boolean, id: number) => {
  setCheckboxState((prev) => {
    let updatedList = prev.map((item) => {
      if (id === item.id) {
        return {
          ...item,
          isChecked: e
        };
      }
      return item;
    });
    return updatedList;
  });
};

My second question is more of a generic Javascript one. This function has three return statements. Is each function returning to the parent function?

To see the rest of the code please see this CodeSandbox

2

Answers


  1. You should replace list with your state value (checkboxState)

    let updatedList = checkboxState.map((item) => { // HERE
      if (id === item.id) {
        return {
          ...item,
          isChecked: e,
        };
      }
      return item;
    });
    setCheckboxState(updatedList);
    

    This will allow you to select multiple options based on your current state not the list initial value that will never change

    Login or Signup to reply.
  2. This code can only select one Item at a time:

    const selectCheckbox = (e: boolean, id: number) => {
      let updatedList = list.map((item) => {
        if (id === item.id) {
          return {
            ...item,
            isChecked: e,
          };
        }
        return item;
      });
    
      setCheckboxState(updatedList);
    
    };
    

    This is because ID is a single number; and only one item in your List of Items will have an ID that matches the ID submitted as an Argument. When you place the code inside setCheckboxState, the function may be dynamically handling the ID. It’s hard to say without seeing all the code.

    Regarding your second question, a Function will only call it’s Return statement once. That ends the function. For example, this error will never throw:

    const a = (b) => {
     if(b) return true;
    return false:
    throw new Error();
    }
    

    This will return true if b is truthy, otherwise it will return false. if B is truthy, nothing else will execute after "return true"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search