2

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;
Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
  • 5
    just like the error says, you are trying to call a function property of an undefined object. your question has nothing to do with`toFixed`; instead, figure out why `recipe.calories` is undefined – Dan O Jan 04 '20 at 16:06

1 Answers1

2

This is a very common problem. The first time render runs, this.state.activeRecipe.calories will be empty because the fetch call will not have returned yet. So you need to account for that in your render function by only calling toFixed if this.state.activeRecipe.calories exists:

const recipe = this.state.activeRecipe;
const calories = recipe.calories ? recipe.calories.toFixed(2) : null;

Note that you'll also need to adjust what is returned by the render function in this case, i.e. you need to know what to do if this.state.activeRecipe is empty.

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35