Martial
Martial

Reputation: 1562

Update data in parent when added in child in react

I'm new to React. I see a lot of posts for updating children when the parent is updated but I haven't found the opposite.

I have a parent component (MainComponent) fetching and storing data. The form to add data (FormNewSubItem ) is in a child component.

When I submit the form I add a subitem in an item and I want the array of items in main component to store the new data.

In MainComponent.jsx

storeItems(items) {
  // store items in db
}

retrieveItems() {
  // return items from db
}

render {
  return (
    <MainComponent>
     <ListItems items={this.retrieveItems()} />
    </MainComponent>
  )
}

In ListItems.jsx

render {
  return (
    <div>
      {this.props.items.map((item, idx) => <Item item={item} key={idx} />)}
    </div>
  )
}

In Item.jsx

handleNewSubItem = (subItem) => {
  this.props.item.addSubItem(subItem);
  // how to update the 'fetchedItems' in MainComponent ?
}

render {
  return (
    <React.Fragment>
      <div className="title">{this.props.item.title}</div>
      <div className="content">
        <ListSubItems subitems={this.props.item.subitems}>
          <FormNewSubItem handleNewSubItem={thid.handleNewSubItem} />
        </ListSubItems>
      </div>
    </React.Fragment>
  )
}

Upvotes: 1

Views: 56

Answers (2)

Asher Gunsay
Asher Gunsay

Reputation: 269

Look into using Context and the useContext hook if you don’t want to use redux for a simple app.

Upvotes: 0

brycelikesdogs
brycelikesdogs

Reputation: 151

So there are a few ways you can do this. A common way would to connect both components to the same set of data using a library like Redux. But if you just want to do this in React, then you will need to define the function in the top level component and then pass it down as props to the child component.

So the MainComponent.js will have a function like

addSubItem = (item) => {
  // update the state here
}

Then you will pass it down as props to the component you want to use it in, so pass it to the ListItems.js component by

<ListItems items={this.retieveItems()} addSubItem={addSubItem} />

and then again to the Item.js component

<Item item={item} key={idx} addSubItem={this.props.addSubItem}/>

then in the Item component just call it with this.props.addSubItem

Because it is scoped to the top level component, when you call the function in the child components and pass it an item, it will update the state in the parent component

Upvotes: 3

Related Questions