Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating array on child 2, from child 1

child 1 has an array of items

child 2 needs to pass an item object to child 2 to update child 2s item array.

How can I pass this item object to the parent from child 2, and then send it back down to child 1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

parent render:

 <Child1  currentItems={currentItems} />
 <Child2 />

child 1:

 const [currentItems, setCurrentItems] = useState(
    props.currentItems
  );

  // call this from child 2 via parent
  // pass item property to be able to update currentItems
  function updateItem(item: Item) {
    const indexOfItem = currentItems.indexOf(item);
    currentItems[indexOfItem] = item;
    setCurrentItems(currentItems);
  }

child 2:

  function handleItemClick(item: Item) {
    // use this to send to updateItem on child 1 via parent
  }

>Solution :

<Child1  currentItems={currentItems} />

From that code it seems you already have the currentItems in the parent, you should just move the updateItem function from Child1 to the parent, pass it Child2 and then call it inside handleItemClick.

function Parent() {
  const [currentItems, setCurrentItems] = useState([]);

  function updateItem(item: Item) {
    const indexOfItem = currentItems.indexOf(item);
    currentItems[indexOfItem] = item;
    setCurrentItems(currentItems);
  }

  return <>
    <Child1 currentItems={currentItems} />
    <Child2 updateItem={updateItem}/>
  </>
}
function Child1({currentItems}) {
  // there is no need for another currentItems state here
}

and in Child2:

function handleItemClick(item: Item) {
  updateItem(item);
}

Also note that your updateItem function will not trigger a re-render. You should create a new array so that React can tell it has changed. Try setCurrentItems([...currentItems])

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading