I have a reducer in my react native app which ideally should check the state and return if the recipe has been favourited or not. I've tried to create a reducer to return if isFav is true or false for a recipe object in the state. If the recipe is not found in the state it should return false.
I've hit a brick wall trying to figure out how to write the reducer. This is what I have so far.
This is my favids.js reducer
import { TOGGLE, IS_FAVOURITE } from '../actions'
export const favids = (state = [], action) => {
const { type, recipeid } = action
const newRecipe = {
recipeid,
is_fav: true,
}
switch (type) {
case TOGGLE: {
// console.log(`Toggle State = ${JSON.stringify(state)}`)
// console.log(`Toggle recipe id : ${recipeid}`)
return state.findIndex(recipe => recipe.recipeid === recipeid) === -1 ?
[...state, newRecipe] :
state.map(recipe =>
recipe.recipeid === recipeid ?
{ ...recipe, is_fav: !recipe.is_fav } : recipe
)
}
case IS_FAVOURITE: {
//console.log(`Is Favourite state =${JSON.stringify(state)}`)
return state.map(recipe =>
recipe.recipeid === recipeid ?
recipe.is_fav : state
)
}
default:
return state
}
}
This is my actions.js
export const TOGGLE = 'TOGGLE'
export const toggleFavId = id => ({
type: 'TOGGLE',
recipeid: id
})
export const IS_FAVOURITE = 'IS_FAVOURITE'
export const isFavourite = id => (
{
type: 'IS_FAVOURITE',
recipeid: id
}
)
I'm trying to modify the is_favourite reducer to return a true or false which is the value of the is_fav property of the recipe object saved down in the state.
I'm trying to call this in the useEffect of the visible component while rendering the component.
This is the favicon.js file
import React, {useState, useEffect} from 'react'
import { FontAwesome } from '@expo/vector-icons'
import { View, TouchableOpacity,StyleSheet, Text, Alert } from 'react-native'
const FavIcon = ({recipeid, onToggle, isFavourite, text}) => {
const [isFavNew, setFavNew] = useState(false)
const toggleFav = (recipeid) =>{
setFavNew(!isFavNew)
onToggle(recipeid)
}
useEffect(() => {
console.log("Entered useEffect")
console.log(`Recipeid = ${recipeid}`)
console.log(`Favicon UseEffect IS Favourtie Recipe id:> ${JSON.stringify(isFavourite(recipeid))}`)
**// if (recipeid > 0)
// setFavNew((isFavourite(recipeid))
// else {
// setFavNew(false)
// }**
},[])
// console.log(`Is Favourite in Favicon is = ${isFavourite(recipeid)}`)
return (
<View>
<TouchableOpacity style={styles.favItem} onPress={() => toggleFav(recipeid)}>
<FontAwesome name={isFavNew === true ? 'heart' : 'heart-o'} size={40} color='red' />
<Text> {text}</Text>
</TouchableOpacity>
</View>
)
}
export default FavIcon