I'm defining a const variable called filteredRecipes and I'm trying to use it to setState. The console is reporting that filteredRecipes is undefined,
Uncaught ReferenceError: filteredRecipes is not defined
I can't see what I'm doing wrong? Any help is greatly appreciated.
updateRecipeList () {
const filteredRecipes = fetch('http://www.***.co.uk/rest/recipes.json')
.then(res => res.json())
.then(json => {
json.results.filter(
function (recipe) {
return (
this.state.currentRecipe === "" || recipe.pagetitle.toLowerCase().indexOf(this.state.currentRecipe.toLowerCase()) !== -1
)
}.bind(this)
);
});
this.setState({
recipes: filteredRecipes
});
}
The reason why is because your this.setState
is outside of the Promise, meaning that I will not wait for the Promise to finish before trying to execute that code. Which means that the variable will be undefined.
You can solve this by putting it inside the promise like so:
updateRecipeList() {
const filteredRecipes = fetch('http://www.***.co.uk/rest/recipes.json')
.then(res => res.json())
.then(json => {
json.results.filter(
function(recipe) {
return (
this.state.currentRecipe === "" || recipe.pagetitle.toLowerCase().indexOf(this.state.currentRecipe.toLowerCase()) !== -1
)
}.bind(this)
);
this.setState({
recipes: filteredRecipes
});
});
}