Home > Back-end >  how to make two calls to mongodb to get data and pass it to a son component?
how to make two calls to mongodb to get data and pass it to a son component?

Time:11-17

im building an app that the user can save his favorites assets that published for rent ... and watch them in another page called favorites.

class Favorites extends Component {


  state = {

    cards: [],


  };

  async componentDidMount() {

    const { data } = await userMethods.getUserFavorites();

    const favoritesArray = data.favorites;

    for (var cardId of favoritesArray) {
      const { data } = await cardService.getFavoritesCards(cardId);
      let arr = [];
      arr.push(data);
      console.log(arr);
      this.setState({ cards: arr })
    }


  }

  render() {

    const { cards } = this.state;
    console.log(cards);

    return (

      <div className="container" >
        <PageHeader>My favorites</PageHeader>
        <div className="row">
          <div className="col-12 mt-4">
            {cards.length > 0 && <p>This are the chosen one's...</p>}
          </div>
        </div>
        <div className="row">
          {cards.length > 0 &&
            cards.map(card => <CardFavorite card={card} key={card._id} />)
          }
        </div>
      </div>

    );
  }
}

export default Favorites;

in this request ===> const { data } = await userMethods.getUserFavorites(); i get an array with the cards id's .. i need to make another request to an endpoint that retrives the cards with the given id's.. but when i pass it to the son component it renders me just one card .. please help

CodePudding user response:

Every iterate in for loop you create a new empty array and push received data to that and set that to state. next iterate, again you create a new empty array.

you should first get the current state and push new data to it then save it in the state

 for (var cardId of favoritesArray) {
  const { data } = await cardService.getFavoritesCards(cardId);
  let arr = [...this.state.cards];
  arr.push(data);
  console.log(arr);
  this.setState({ cards: arr })
}
  • Related