0

I'm having trouble trying to save some data I'm getting from the CockTaiDB API into my Meteor Collection

state = {
randomCocktail: []
};

async componentDidMount() {
try {
  const res = await fetch(
    'https://www.thecocktaildb.com/api/json/v1/1/random.php'
  );
  const randomCocktail = await res.json();
  this.setState({
    randomCocktail: randomCocktail.drinks
  });
} catch (e) {
  console.log(e);
 }
}

addDrink = (cocktail) => {
Drinks.insert({
  name: cocktail.strDrink,
  instructions: cocktail.strInstructions,
  image: cocktail.strDrinkThumb
 });
};

{this.state.randomCocktail.map((cocktail) => {
      return (
        <div key={cocktail.idDrink}>
          <h1>{cocktail.strDrink}</h1>
          {cocktail.strInstructions}
          <img src={cocktail.strDrinkThumb} alt="" />
          <button onClick={this.addDrink}>Add Drink</button>
        </div>
      );
    })}

This is my function to save into the collection but all I'm getting is a new entry with an id. I used axios.get to retrieve the data, should I use axios.post somehow to save it into my Drinks collection?

Edit: State and api call. Map with the button to add name, image, and instruction.

mwlai
  • 71
  • 1
  • 9
  • Add `console.log(cocktail)` above `Drinks.insert(...)`. Do the desired attributes exist at that point in the code? – Kyle Richardson Apr 04 '18 at 17:24
  • No, I get a Proxy {dispatchConfig{...}, isDefaultPrevented: ƒ, isPropagationStopped: ƒ, _dispatchListeners: ƒ, …}[[Handler]]: Object[[Target]]: SyntheticMouseEvent[[IsRevoked]]: false – mwlai Apr 04 '18 at 17:45
  • Going to need to see more code. Please provide the code where you invoke the `addDrink` method, and the passing of the `cocktail` reference into the method. It would seem you're passing the unresolved promise into the method though. – Kyle Richardson Apr 04 '18 at 18:05
  • I haven't created any methods, I haven't removed insecure. That's the function I thought would post the results into my collection. – mwlai Apr 04 '18 at 18:20
  • You shouldn't have to `await` res.json(), that is a synchronous method. I still don't see where you use the `addDrink` method. In your `componentDidMount`, adjust `this.setState({randomCocktail: randomCocktail.drinks });` to `this.setState({randomCocktail: randomCocktail.drinks }, ()=>{console.log(this.state.randomCocktail)});` and inspect what state looks like. – Kyle Richardson Apr 04 '18 at 18:35
  • The state is now the returned data which has been working as expected. Idk why but now I understood what you meant by not seeing the method. addDrink is the function for Drinks.Insert and I made a button to click in hopes of adding to collection. – mwlai Apr 04 '18 at 21:42

0 Answers0