I would like to ask about the toFixed() method and its usage. I have a const called calories, which is a numeric data and I would like to round it to number with 2 decimal places.
const recipe = this.state.activeRecipe;
const calories = recipe.calories.toFixed(2);
console.log(calories);
I'm getting an error saying Uncaught TypeError: Cannot read property 'toFixed' of undefined
Anyone knows how to fix this or if there is any method that I could use? Thank you!
The whole code:
import React, { Component } from "react";
class Recipe extends Component {
state = {
activeRecipe: []
}
componentDidMount = async() => {
const title = this.props.location.state.recipe;
const req = await fetch
(`https://api.edamam.com/search?q=${title}&app_id=${API_ID}&app_key=${API_KEY}`);
const res = await req.json();
this.setState({ activeRecipe: res.hits[0].recipe});
console.log(this.state.activeRecipe);
}
render() {
const recipe = this.state.activeRecipe;
const calories = recipe.calories.toFixed(2);
console.log(calories);
return (
<div className="container">
<h3 className="active-recipe">{recipe.label}</h3>
<div className="container">
{recipe.ingredients && recipe.ingredients.map(ingredient => {
return (
<p>{ingredient.text}</p>
);
})}
</div>
</div>
);
}
}
export default Recipe;