0

I want to create a function that can be general as possible but It doesn't work now.

I have two case :

  • Check if the state of a state is not empty or true and if my item is equal to him, I want to reset him by calling resetState() and set to false and empty string

  • Check if the state of a state is not empty and if my item is equal to him, I want to reset him by calling resetState()and the empty string

My problem is : I try to replace stateItem.checkedA by something like stateItem.item to avoid repetitions but doesn't work for me, is it possible in react to do that ?

This is what I have :

const [stateBoolean, setStateBoolean] = React.useState({
    checkedA: false,
    checkedB: false
  });

const [stateItem, setStateItem] = React.useState({
    checkedA: "",
    checkedB: "toto",
    checkedC: "onlyHere not in Boolean"
  });

  const check = (listState) => {
    listState.map(item => {
      (stateBoolean.checkedA === true || stateItem.checkedA !== "") &&
      item === "checkedA"
        ? (resetChange("checkedA", "stateItem"),
          resetChange("checkedA", "stateBoolean"))
        : null;
      (stateBoolean.checkedB === true || stateItem.checkedB !== "") &&
      item === "checkedB"
        ? (resetChange("checkedB", "stateItem"), resetChange("checkedB", "stateBoolean"))
        : null;
      stateItem.checkedC !== "" && item === "checkedC"
        ? resetChange("checkedC", "stateItem")
        : null;
    });
  };

What I expected, but not working:

const checkWanted = (listState) => {
    listState.map(item => {
      (stateBoolean.item === true || stateItem.item !== "") &&
      (item === "checkedB" || item === "checkedA")
        ? (resetChange(item, "stateItem"), resetChange(item, "stateBoolean"))
        : null;
      stateItem.checkedEOther !== "" && item === "checkedEOther"
        ? resetChange(item, "stateItem")
        : null;
    });
  };

Any idea?

flopic
  • 1,039
  • 4
  • 10
  • 14

1 Answers1

0

Use stateBoolean[item] instead, you can access properties of an object like an array

The function map return a new Array mdn description If you want to iterate on a array and do something you should use forEach or a for loop.

Loïck M
  • 358
  • 1
  • 6
  • I think I don't explain properly or I don't get It : I try to access to another props with my Item of map, like accessing to stateBoolean.item where item will be equal to a "prop" existing in stateBoolean like stateBoolean.checkedB (so item can be equal to checkedB, checkedC... every round of the map) – flopic May 29 '19 at 11:55
  • Use stateBoolean[item] instead, you can access key of an object like an array. My response was about using "listState.forEach(item => {" instead of "listState.map(item => {" – Loïck M May 31 '19 at 05:14