I've been struggling for a long time with this one. I was trying to create a reducer to be able to add an item into a favourties list. I can create a state object and save down the id into the state object using useState, but have hit a brick wall trying to do the same with Redux.
this is my favicon.js
import React, {useState} from 'react'
import { FontAwesome } from '@expo/vector-icons'
import { View, TouchableOpacity,StyleSheet, Text, Alert } from 'react-native'
import { connect } from 'react-redux'
import { toggleFavId, isFavourite } from '../actions'
const FavIcon = ({recipeid, toggle, isFav, text}) => {
const [isFavNew, setFavNew] = useState(false)
const toggleFav = (recipeid) =>{
setFavNew(!isFavNew)
console.log(`Entered toggle ${recipeid} isfavnew = ${isFavNew}`)
}
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>
)
}
const mapStateToProps = (state) =>({
favids: state.favids,
})
const mapDispatchToProps = (dispatch) => ({
toggle: (recipeid) => dispatch(toggleFavId(recipeid)),
isFav: (recipeid) => dispatch(isFavourite(recipeid)),
})
export default connect(mapStateToProps,mapDispatchToProps)(FavIcon)
This is my reducer but its incorrect as I cant seem to be able to pull the state for an item.
import {TOGGLE, IS_FAVOURITE} from '../actions'
export const favids = (state=[], action) => {
const {type, recipeid} = action
const newRecipe = {
id: recipeid,
is_fav: false,
}
switch (type) {
case TOGGLE: {
if (state.includes(recipeid)===true) {
return state.filter((state) => state.id !== recipeid)
}
else {
return state.concat(recipeid)
}
}
case IS_FAVOURITE: {
return state.map(item=>{
if(item.recipeid === recipeid){
item.is_fav = !item.is_fav
}
})
}
default:
return state
}
}
I am trying to create the reducer to replicated the toggleFav function in the FavIcon.
const toggleFav = (recipeid) =>{
setFavNew(!isFavNew)
console.log(Entered toggle ${recipeid} isfavnew = ${isFavNew})
}
All I am trying to do is toggle the recipe in the favourites if clicked on the icon. Any help would be greatly appreciated.