Home > Software design >  How to get an object out of a useState array?
How to get an object out of a useState array?

Time:02-24

I have a table with a row that has a checkbox, and I have an object called an ellipse.

I need to make the ellipse object to enter the savedEllipse array (which uses useState) as soon as I click on the checkbox.

In the test I did, I see that the ellipse object did go into the array, but now I have to make it out of the array once I uncheck the checkbox, and I couldn't quite figure out how I could do that with an object type like the ellipse object I have here.

You can see that I did the same thing with setChekcedState, which makes sure that the name of the checkbox comes in and out of the checkedState array, and it works great, but when I tried to do it with the ellipse object the same way, it did not work.

Do you have an idea?

I found (here in StackOverflow) a few questions that are close to this, but none of them dealt with this specific problem, so don't get confused

Here's the code:

export default function App() {

const [checkedState, setChekcedState] = useState([]);

const [savedEllipse, setSavedEllipse] = useState([]);

const ellipse = {
  a: [12, 22],
  b: [22, 55],
  c: [42, 68]
};

const ellipseSet = (e) => {
        const { checked, name } = e.target;
        if (checked) {
            setChekcedState((oldState) => [...oldState, name]);
            setCheckedEllipse((oldState) => [...oldState, ellipse]);
        } else {
            setChekcedState((oldState) => oldState.filter((row) => row !== name));
        }
};

return (

<TableContainer>
      <Table aria-label="simple table">
        <TableBody >
            <TableRow>
              <TableCell padding="checkbox">
                <Checkbox
                  onChange={ellipseSet}
                  checked={checkedState.includes((row.id).toString())}
                  name={1}/>
              </TableCell>
            </TableRow>
          
        </TableBody>
      </Table>
    </TableContainer>
  );  
}

CodePudding user response:

use these 2 functions to check the equality of the objects

 function isEqual(object1, object2) {
      return arrayEquals(object1.a,object2.a) && arrayEquals(object1.b,object2.b) && arrayEquals(object1.c,object2.c);
    }

function arrayEquals(a, b) {
    return Array.isArray(a) &&
        Array.isArray(b) &&
        a.length === b.length &&
        a.every((val, index) => val === b[index]);
}

Then we can set the state in ellipse list :)

setCheckedEllipse((oldState) => oldState.filter((row) => !isEqual(row,ellipse));
  • Related