I have a React Component called Recipe. It reads in the Recipe ID with this.props.match.id and puts it into state. I have a function called useRecipe, which I want activated onClick and will eventually do some database stuff. However, I keep getting an error I think because of the asynchronous nature of the API call. It reads my first variable as undefined because state hasn’t been populated yet. I was wondering if there was a fix to this. The component is below:
import React from "react";
import axios from "axios";
class Recipe extends React.Component {
// console.log(grep)
state = {
data: []
}
handleUseRecipe = () => {
let strIngredients = this.state.data.Ingredients;
console.log(strIngredients)
let arIngredients = strIngredients.split(", ");
let strAmounts = this.state.data.Amounts;
let arAmounts = strAmounts.split(", ");
let strUnits = this.state.data.Units;
let arUnits = strUnits.split(", ");
console.log(arIngredients);
console.log(arAmounts);
console.log(arUnits);
// For Each
}
componentDidMount(){
const id = this.props.match.params.id
axios.get(`http://localhost:4000/recipe/${id}`)
.then(res => {
this.setState({
data: res.data
} )
})
}
render(){
console.log(this.state.data.Ingredients)
return (
<div>
<span>{JSON.stringify(this.state.data)}</span>
<button
onClick={this.handleUseRecipe()}
>Use Recipe</button>
</div>
)
}
}
export default Recipe;
And here is the error. Let me know if anyone can help! I will be here.