pKay
pKay

Reputation: 1840

Updating sibling component on an event in react js

I have a simple app which consists of a home component , an add component , Listing component. Home component has listing and add component. In add component i am adding some items to local storage and in listing component i am retrieving those items and showing as a list. Listing component doesn't have any props, it directly gets the data from local storage and returns ul list. I wanted to know, is there a way that when I save my data to local storage, at the same time my list should be updated that means there has to be some way by that if i click on save button the listing component should render with updated list. Can i trigger the render method of any component manually without using states.

Upvotes: 0

Views: 606

Answers (2)

kumaran ragunathan
kumaran ragunathan

Reputation: 447

There is a method called this.forceUpdate() to re-render , so just call this method after each element added to local storage

addItem(elm){    
 localStorage.yourArray.push(elm);
 this.forceUpdate();
}

Upvotes: 0

Dave Bitter
Dave Bitter

Reputation: 101

this.forceUpdate() does work, but is in most cases a cheap fix which you want to avoid. You could have a the listings in two places: Local Storage for the actual saving, the state to trigger re-rendering when needed. Your app might look something like this:

constructor() {
  super()

  this.state = {
    listings: []
  }
}

componentWillMount() {
  localStorage.getItem('listings')

  this.setState({ listings })
}

saveListing(newListing) {
  const listings = this.state.listings.concat([])

  listings.push(newListing)

  localStorage.setItem('listings', listings)
  this.setState({ listings })
}

render() {
  return(
    <div>
      <ul>
        {
          this.state.listings.map(listing => {
            return(
              <ListingComponent key={listing.id} listing={ ...listing } />
            )
          })
        }
      </ul>
      <AddListingComponent addListing={(newListing) => this.saveListing(newListing)} />
    </div>
  )
} 

Upvotes: 1

Related Questions