U. Watt
U. Watt

Reputation: 724

How to properly update the screen based on state variables

I'm new to react and I'm learning how to fetch data from an api once the user clicks on a button. Somehow, I've gotten everything to work, but I don't think I'm using the library properly.

What I've come up with:

class App extends React.Component {

  state = {
    recipe: null,
        ingredients: null
    }

    processIngredients(data) {
        const prerequisites = [];
        const randomMeal = data.meals[0];

        for(var i = 1; i <= 20; i++){
            if(randomMeal['strIngredient' + i]){
                prerequisites.push({
                    name: randomMeal['strIngredient' + i],
                    amount: randomMeal['strMeasure' + i]
                })
            } 
        }
        this.setState({
      recipe: data,
            ingredients: prerequisites,
        })
        console.log(prerequisites[0].name)
    }

  getRecipes = () => {
    axios.get("https://www.themealdb.com/api/json/v1/1/random.php").then(
      (response) => {
        this.processIngredients(response.data);
      }
    )
  }

  render() {
    return (
      <div className="App">
        <h1>Feeling hungry?</h1>
       <h2>Get a meal by clicking below</h2>
       <button className="button" onClick={this.getRecipes}>Click me!</button>
       {this.state.recipe ? <Recipe food={this.state.recipe} 
          materials={this.state.ingredients} /> : <div/>}
      </div>
    );
  }
}

The way I'm checking the value of state.recipe in render() and invoking the Recipe component, is it correct? Or does it seem like hacked together code? If I'm doing it wrong, what is the proper way of doing it?

Upvotes: 0

Views: 93

Answers (1)

Rafael Dowling Goodman
Rafael Dowling Goodman

Reputation: 913

It's really a minor nit, but in this case you can use an inline && logical operator since there's nothing to render for the "false" case:

{this.state.recipe && <Recipe food={this.state.recipe} materials={this.state.ingredients} />}

Checkout https://reactjs.org/docs/conditional-rendering.html for more info.

Upvotes: 2

Related Questions