abhinav chavali
abhinav chavali

Reputation: 163

refresh component state every time it is rendered react

I have an API running and I am trying to fetch that to get some information about some products. I am using react router to route the products and using that to fetch the API. However, when I try clicking on a different product the information from the previous product remains no matter what I do.

Here is my fetch:

componentWillMount(){
let id = this.props.params.id + 3;
let url = 'http://localhost:8000/api/item/' + id + '/';
return fetch(url)
  .then(results => results.json())
  .then(results => this.setState({'items': results}))
  .catch(() => console.log(this.state.items));

and where I call the fill the information

render() {
return (
  <div className="itemPageWrapper">
    <div className="itemImgWrapper" />
    <div className="itemInfoWrapper">
      <Link className="backLink" to="/">
        <span className="small">
          <svg fill="#000000" height="13" viewBox="0 0 18 15" width="13" xmlns="http://www.w3.org/2000/svg">
            <path d="M7 10l5 5 5-5z"/>
            <path d="M0 0h24v24H0z" fill="none"/>
          </svg>
        </span>All Items
      </Link>
      <h3 className="itemName">{this.state.items[Number(this.state.id)].name}</h3>
      <p className="itemCost frm">{this.state.items[Number(this.state.id)].price}</p>
      <p className="description">
        {this.state.items[Number(this.state.id)].description}
      </p>
      <p className="seller frm">By <span>{this.state.items[Number(this.state.id)].brand}</span></p>
    <button className="reqTradeBtn normalBtn">Order</button>
    </div>
  </div>

I receive an error saying TypeError: Cannot read property 'name' of undefined if I change anything. I am using a +2 because my API starts at 3. How would I make this work for all products

Upvotes: 0

Views: 78

Answers (1)

Mykola Prymak
Mykola Prymak

Reputation: 447

You should check if you had that items loaded

this.state.items[Number(this.state.id)]

render() {
   const item = this.state.items[Number(this.state.id)];

   if (!item) {
      return 'Loading';
   }

   return (
       <div className="itemPageWrapper">
       ......
       </div>
   );
}

Also you rewrite state.items each time. Maybe you should use some Redux to store this collection globally.

Upvotes: 1

Related Questions