admin管理员组

文章数量:1123003

I have multiple forms as grandchildren, and all forms are submitted at once by clicking the Submit button available in the parent.

To achieve this, we need to have a state called forms in the parent, which is an array of objects. Each object corresponds to one form. Additionally, for the onChange of each form, we need to pass the data to the parent.

The issue I encounter is that when changing the data in each form, I want to check if this form already exists and update it, rather than adding a new one to the array. For this, we need an identifier for each form, which should be passed along with the object.

I figured out that I can use a counter in the parent. This counter will increment for each grandchild we have on the screen, and we can store this counter before incrementing it as the identifier. This way, each form will have a unique identifier like: 0, 1, 2, 3, and so on, depending on which one is rendered first.

Part of my code:

Parent Component:

function Parent({
  userDetails,
  availableViewTypes,
  availableDiscountReason,
}) {
  const [views, setViews] = useState([]);
  const [counter, setCounter] = useState(0);

 const getNextCounter = () => {
    const currentCounter = counter;
    setCounter(counter + 1);
    return currentCounter;
  };


  const handleViewChange = (index, updatedView) => {
    console.log(index);
    setViews((prev) => {
      const newViews = [...prev];
      newViews[index] = updatedView; // Update the specific view by index
      return newViews;
    });
  };

  
  const handleSubmit = () => {
    console.log(views)
  };
  return (
    <div className="form">
      <Box>
        {userDetails.data.length > 0 &&
          userDetails.data.map((p, i) => {
            return (
              <Box key={i}>
                <div className="forms">
                  {p.data.map((payment, index) => (
                    <TypeForm
                      onViewChange={handleViewChange}
                      key={index}
                      data={payment}
                      userDetails={userDetails}
                      getNextCounter={getNextCounter}
                      counter={counter}
                    />
                  ))}
                </div>
              </Box>
            );
          })}
      </Box>

      <Box>
        <LoadingButton
          onClick={handleSubmit}
        >
          Submit
        </LoadingButton>
      </Box>
    </div>
  );
}

export default Parent;

Children Component:

function Child({
  data,
  types,
  onViewChange,
  getNextCounter,
}) {
  return (
      <Box sx={{ display: "flex" }}>
        {types?.length > 0 &&
          types.map((v, i) => (
            <GrandChild
              key={`${data.id}-${v.id}-${i}`}
              onViewChange={onViewChange}
              getNextCounter={getNextCounter}
            />
          )
        )}
      </Box>
  );
}

export default Child;

GrandChild:

function GrandChild({ onViewChange, counter, getNextCounter }) {

  const [formIdentifier, setFormIdentifier] = useState(null);
  const [viewData, setViewData] = useState({
    quantity: 0,
    amount: 0,
    identifier: null,
  });

  const updateViewData = (updates) => {
    setViewData((prev) => {
      const updatedData = { ...prev, ...updates };
      onViewChange(formIdentifier, updatedData);
      return updatedData;
    });
  };
  useEffect(() => {
    const newIdentifier = getNextCounter();
    setFormIdentifier(newIdentifier);
    setViewData((prev) => {
      const updatedData = { ...prev, identifier: newIdentifier };
      return updatedData;
    });
  });

reutrn (
// rest of the code
)

If I pass the getNextCounter function in the dependencies, it will cause an infinite loop. If I don't pass it, the counter will only increment once, so all forms will have the same identifier (which will be 1), and that's absolutely wrong.

Could you please tell me how to do this the right way?

I have multiple forms as grandchildren, and all forms are submitted at once by clicking the Submit button available in the parent.

To achieve this, we need to have a state called forms in the parent, which is an array of objects. Each object corresponds to one form. Additionally, for the onChange of each form, we need to pass the data to the parent.

The issue I encounter is that when changing the data in each form, I want to check if this form already exists and update it, rather than adding a new one to the array. For this, we need an identifier for each form, which should be passed along with the object.

I figured out that I can use a counter in the parent. This counter will increment for each grandchild we have on the screen, and we can store this counter before incrementing it as the identifier. This way, each form will have a unique identifier like: 0, 1, 2, 3, and so on, depending on which one is rendered first.

Part of my code:

Parent Component:

function Parent({
  userDetails,
  availableViewTypes,
  availableDiscountReason,
}) {
  const [views, setViews] = useState([]);
  const [counter, setCounter] = useState(0);

 const getNextCounter = () => {
    const currentCounter = counter;
    setCounter(counter + 1);
    return currentCounter;
  };


  const handleViewChange = (index, updatedView) => {
    console.log(index);
    setViews((prev) => {
      const newViews = [...prev];
      newViews[index] = updatedView; // Update the specific view by index
      return newViews;
    });
  };

  
  const handleSubmit = () => {
    console.log(views)
  };
  return (
    <div className="form">
      <Box>
        {userDetails.data.length > 0 &&
          userDetails.data.map((p, i) => {
            return (
              <Box key={i}>
                <div className="forms">
                  {p.data.map((payment, index) => (
                    <TypeForm
                      onViewChange={handleViewChange}
                      key={index}
                      data={payment}
                      userDetails={userDetails}
                      getNextCounter={getNextCounter}
                      counter={counter}
                    />
                  ))}
                </div>
              </Box>
            );
          })}
      </Box>

      <Box>
        <LoadingButton
          onClick={handleSubmit}
        >
          Submit
        </LoadingButton>
      </Box>
    </div>
  );
}

export default Parent;

Children Component:

function Child({
  data,
  types,
  onViewChange,
  getNextCounter,
}) {
  return (
      <Box sx={{ display: "flex" }}>
        {types?.length > 0 &&
          types.map((v, i) => (
            <GrandChild
              key={`${data.id}-${v.id}-${i}`}
              onViewChange={onViewChange}
              getNextCounter={getNextCounter}
            />
          )
        )}
      </Box>
  );
}

export default Child;

GrandChild:

function GrandChild({ onViewChange, counter, getNextCounter }) {

  const [formIdentifier, setFormIdentifier] = useState(null);
  const [viewData, setViewData] = useState({
    quantity: 0,
    amount: 0,
    identifier: null,
  });

  const updateViewData = (updates) => {
    setViewData((prev) => {
      const updatedData = { ...prev, ...updates };
      onViewChange(formIdentifier, updatedData);
      return updatedData;
    });
  };
  useEffect(() => {
    const newIdentifier = getNextCounter();
    setFormIdentifier(newIdentifier);
    setViewData((prev) => {
      const updatedData = { ...prev, identifier: newIdentifier };
      return updatedData;
    });
  });

reutrn (
// rest of the code
)

If I pass the getNextCounter function in the dependencies, it will cause an infinite loop. If I don't pass it, the counter will only increment once, so all forms will have the same identifier (which will be 1), and that's absolutely wrong.

Could you please tell me how to do this the right way?

Share Improve this question edited 35 mins ago Kirstie Wilkinson 1721 gold badge1 silver badge11 bronze badges asked 59 mins ago abdelrahman-assoumabdelrahman-assoum 235 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

you can try using refs

const counterRef = useRef(0);

const getNextCounter = () => {
    const currentCounter = counterRef.current;
    counterRef.current = currentCounter + 1; // Update the ref directly
    return currentCounter;
  };

in the grandchild comp use an empty dependency array [] for the useEffect() so it only runs on rendering time

 useEffect(() => {
    const newIdentifier 
.
.
.
  }, []);

Hope this is what you asked

本文标签: javascriptUsing counter as an identifier for grandchildren in ReactStack Overflow