Home > Net >  Updating array on child 2, from child 1
Updating array on child 2, from child 1

Time:06-20

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.

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
  }

CodePudding user response:

<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])

  • Related