Michael Stotzer
Michael Stotzer

Reputation: 43

react native TypeError (..) is not a function

I want to display an image and the according text from an object chosen randomly from an array.

Basically that's the chain I plan on using to get both the name and the image: ingredient <- ingredientArray <- getRandomIngredient <- getIngredientImage (& getIngredientName)

I'm sure there is something basic I just don't get about object oriented programming, but I can't get it to work.

ingredientArray:

const ingredient1 = new Ingredient("green salad", require('./app/components/img/base/green_salad.jpg'));
const ingredient2 = new Ingredient("mixed salad", require('./app/components/img/base/mixed_salad.jpg'));
var ingredientArray = ["ingredient1", "ingredient2"]

getRandomIngredient:

function getRandomIngredient (arr){
  if (arr && arr.length) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
}

class Ingredient:

function Ingredient (ingredientName, ingredientImage){
  this.ingredientName = ingredientName;
  this.ingredientImage = ingredientImage;

  Ingredient.prototype.getIngredientName = function(){
    return this.ingredientName;
  }

  Ingredient.prototype.getIngredientImage = function(){
    return this.ingredientImage;
  }
}

What I would like to do:

<Image source = {getRandomIngredient(ingredientArray).getIngredientImage()}

But I get the following error message:

TypeError: getRandomIngredient(...).getIngredientImage is not a function

If I call the function getIngredientImage() directly, I get a working result:

<Image source = {base1.getIngredientImage()} />

Upvotes: 1

Views: 4235

Answers (2)

Craig E
Craig E

Reputation: 1

Try adding the variables to your "ingredientArray" instead of the "string" identifiers that you are using for your constants. IE change

var ingredientArray = ["ingredient1", "ingredient2"]

to

var ingredientArray = [ingredient1, ingredient2]

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 223194

There's no getIngredientImage method because getRandomIngredient(ingredientArray) doesn't return an instance of Ingredient. Because ingredientArray is an array of strings, not Ingredient instances.

It should be:

var ingredientArray = [ingredient1, ingredient2]

Upvotes: 1

Related Questions