Petra Jakubcova
Petra Jakubcova

Reputation: 105

How to use toFixed() method

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;

Upvotes: 2

Views: 923

Answers (1)

Ismael Padilla
Ismael Padilla

Reputation: 5566

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.

Upvotes: 2

Related Questions