I have a helper function:
export async function isFavorite(id) {
try {
let favorites = await AsyncStorage.getItem("@rn-food-app:favorites");
if (favorites) {
return JSON.parse(favorites).includes(id);
}
return false;
} catch (error) {
return false;
}
}
which I'm calling like this:
class DetailScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
recipe: null,
isFavorite: false,
};
}
componentDidMount() {
const { route } = this.props;
if (route.params && route.params.recipeId) {
const recipe = getRecipe(route.params.recipeId);
this.setState(
{
recipe,
},
() => {
this.checkIfFavorite();
}
);
}
}
checkIfFavorite() {
const { recipe } = this.state;
console.log(isFavorite(recipe.id));
}
... ... ...
but the console.log() returns something like this
Promise {
"_U": 0,
"_V": 0,
"_W": null,
"_X": null,
}
instead of a bool.
I can make it work like this:
export async function isFavorite(id) {
try {
return await AsyncStorage.getItem("@rn-food-app:favorites");
} catch (error) {
return false;
}
}
and then in the DetailScreen component
checkIfFavorite() {
const { recipe } = this.state;
isFavorite(recipe.id)
.then((res) => {
const favorite = JSON.parse(res).includes(recipe.id);
console.log(favorite);
})
.catch((err) => console.log(err));
}
This works but why doesn't the approach above work? I wanted to extract all this logic into a helper function so I can simply call isFavorite: bool inside my components without extra logic.