How to update a single item in FlatList - React Native - react-native

In my case I am writing a Facebook clone like application, but much simpler. I put each item in FlatList and render them.
To "like" a post, I press the "like" button on the post and the "like" button turns yellow and the likes count increase by 1 ( Also I call addLike API Function after clicking ), I press it again, it turns gray and likes count decrease by one ( Also I Call removeLike API Funtion ).
This is what I have so far: I store all the loaded posts with redux - this.props, each post has a property called "liked", which is boolean, indicating whether this user has liked this post or not, when user presses "like", Now I doing when user like the post I call the addLike() action and fetch all the posts to feed again. I want to do this without fetching data again and again
FlatList Component
<FlatList
style={styles.postList}
data={this.props.postData}
extraData={this.props}
maxToRenderPerBatch={10}
keyExtractor={item => {
return item.id;
}}
ItemSeparatorComponent={() => {
return <View style={styles.separator} />;
}}
renderItem={post => {
const item = post.item;
this.state.userisLiked = item.likedUsers.find(
user => user.id == this.state.userDetails.id,
);
// console.log('Returning Is Liked ', isLiked);
return (
<View style={styles.card}>
<View>
{item.postImage ? (
<TouchableOpacity
onPress={() =>
this.showSelectedImageFullView(item.postImage)
}>
<ImageBackground
style={styles.cardImage}
source={{
uri: Strings.AWSS3_POST_IMAGE + item.postImage,
}}>
<View style={styles.overlay} />
</ImageBackground>
</TouchableOpacity>
) : (
<View></View>
)}
</View>
<View style={{flexDirection: 'row'}}>
<Image
source={
item.user.profilePicture
? {
uri:
Strings.AWSS3_USER_PROFILE_AVATAR +
item.user.profilePicture,
}
: Images.IMAGE_PLACEHOLDER
}
style={styles.postUserImage}
/>
<View style={{flexDirection: 'column'}}>
<Text style={styles.postUserName}>
{item.user.firstName} {item.user.lastName}
</Text>
<TimeAgo
style={styles.postedTime}
time={item.createdAt}
interval={20000}
/>
</View>
<TouchableOpacity
style={styles.postMoreInfoIcon}
onPress={() => this.toggleModal(item)}>
<Image
source={Images.POST_MORE_INFO}
style={styles.postMoreInfoIcon}
/>
</TouchableOpacity>
</View>
<TouchableOpacity onPress={() => this.homeMoreInfoScreen(item)}>
<View style={{flexDirection: 'column'}}>
<Text style={styles.postTitle}>{item.title}</Text>
<Text style={styles.postBody} numberOfLines={2}>
{item.description}
</Text>
</View>
</TouchableOpacity>
<View style={styles.cardFooter}>
<View style={{flexDirection: 'row'}}>
<TouchableOpacity
onPress={() => {
this.handleUserLikes(item);
}}>
{this.state.userisLiked ? (
<Image
source={Images.POST_LIKE_CHECKED}
style={{
width: 20,
height: 20,
resizeMode: 'contain',
}}
/>
) : (
<Image
source={Images.POST_LIKE_UNCHECKED}
style={{
width: 20,
height: 20,
resizeMode: 'contain',
}}
/>
)}
</TouchableOpacity>
<Text
selectable={true}
onPress={() => this.toggleLikeModal(item)}
style={{
fontFamily: AppStyles.primaryFont,
fontSize: 15,
color: AppStyles.colorWhite,
marginLeft: 5,
}}>
{item.likesCount} Likes
</Text>
</View>
<View style={{flexDirection: 'row', marginLeft: 20}}>
<TouchableOpacity
onPress={() => this.homeMoreInfoScreen(item)}>
<Image
source={Images.POST_COMMENT}
style={{width: 20, height: 20, resizeMode: 'contain'}}
/>
</TouchableOpacity>
<Text
selectable={true}
onPress={() => this.homeMoreInfoScreen(item)}
style={{
fontFamily: AppStyles.primaryFont,
fontSize: 15,
color: AppStyles.colorWhite,
marginLeft: 5,
}}>
{item.commentsCount} Comments
</Text>
</View>
<View
style={{
flexDirection: 'row',
marginLeft: 10,
position: 'absolute',
right: 100,
top: 20,
}}>
</View>
<View
style={{
flexDirection: 'row',
marginLeft: 10,
position: 'absolute',
right: 10,
top: 20,
}}>
<TouchableOpacity
onPress={() => this.homeMoreInfoScreen(item)}>
<Text
style={{
fontFamily: AppStyles.primaryFont,
fontSize: 15,
color: AppStyles.colorWhite,
}}>
Comment
</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}}
/>
Handle User Like Action
//Add Likes to selected post click listner
handleUserLikes = item => {
//Check user already liked the post
const isLiked = item.likedUsers.find(
user => user.id == this.state.userDetails.id,
);
if (isLiked) {
this.props.removeLikeFromPost(item.id, this.state.user_token);
this.props.fetchPostData(this.state.user_token);
} else {
this.props.addLikeToPost(
item.id,
this.state.user_token,
this.state.userDetails.id,
);
this.props.fetchPostData(this.state.user_token);
}
};

Assuming that the items are available as props. You can handle the data alteration in the reducer instead of your React component. first what you have to do is
handleUserLikes = item => {
this.props.addLikeToPost({
item_id:item.id,
user_token:this.state.user_token,
user_id:this.state.userDetails.id,
});
};
inside your redux code fire a function that handles the logic.
const userLike =(state,payload)=>{
let Newitem = null;
let item= state.item.find(
user => item.id == payload.item_id
);
let itemIndex = state.item.findIndex(
user => user.id == payload.item_id
);
let isLiked = item.likedUsers.find(user=>user.id===payload.user_id);
if(isLiked){
Newitem = {...item,likedUsers:item.likedUsers.filter(user=>user.id!==payload.user_id)}
} else{
Newitem = {...item,likedUsers:[...item.likedUsers,payload.user_id]}
}
let Newitems = [
state.items.slice(0, itemIndex),
Newitem,
state.items.slice(++itemIndex)
];
return {...state,items:Newitems}
}
This method userLike should be called inside the reducer switch statement which corresponds to your particular action. like this
function appReducer(state = initialState, action) {
switch (action.type) {
.........
case 'YOU_ACTION' :
return userLike(state,action);
}
}
In this manner, you don't have to fetch the items data again and again. But make sure you send the data to the back end saying the post is liked or unliked.
const addLikeToPost = (data) => dispatch => {
// you can send a request to your back end here without Awaiting.
// data is passed from the addLikeToPost method called from you react component.
dispatch({action:'YOU_ACTION',payload:data});
}

First of all thanks to #TRomesh for his answer.
Based on that I found a solution for this issue easily
My Button Action Call
handleUserLikes = item => {
this.props.addLikeToPost({
item_id:item.id,
user_token:this.state.user_token,
user_id:this.state.userDetails.id,
});
};
Redux Reducer Function -> This is the part I edited from above answer
const userLike = (state, payload) => {
console.log('TCL: userLike -> payload', payload.payload);
console.log('TCL: userLike -> state.postData', state.postData);
let item = state.postData.find(user => user.id == payload.payload.item_id);
let local_data = state.postData;
let isLiked = item.likedUsers.find(
user => user.id === payload.payload.user_id,
);
if (isLiked) {
local_data = local_data.map(data => {
if (data.id == payload.payload.item_id) {
data.likesCount = Number(data.likesCount - 1);
}
return data;
});
} else if (isLiked == undefined || isLiked == null) {
local_data = local_data.map(data => {
if (data.id == payload.payload.item_id) {
data.likesCount = Number(data.likesCount + 1);
}
return data;
});
}
return {...state, postData: local_data};
};
Cheers !

Related

how make my hook valid ? Object are not valid as a react child

i'm doing my hook with firestore. I did praticly exactly the same on an ohter page and he works. But this one i have the error : Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection of children, use an array instead.
On my console i can see an empty array like that
cc []
also my hook
async function GetFriendsRequest() {
const [TeamsArray, updateTeamArray] = React.useState([]);
firestore()
.collection("Teams")
// Filter results
.where("uid", "==", await AsyncStorage.getItem("userID"))
.get()
.then((querySnapshot) => {
if (querySnapshot.empty) {
console.log("no documents found");
} else {
querySnapshot.forEach(async (doc) => {
let Teams = doc._data;
TeamsArray.length = 0;
updateTeamArray((arr) => [...arr, Teams]);
console.log("cc", JSON.stringify(TeamsArray));
});
}
});
return (
<View>
{TeamsArray.map((element, key) => {
<View style={{ flex: 1, flexDirection: "row" }}>
<View>
<Text style={{ color: "#5DC1D3" }}>
{element.MembersList.nickName}
</Text>
<Text style={{ color: "#5DC1D3" }}>{element.Activity} </Text>
</View>
</View>;
})}
</View>
);
}
Something is wrong ?
Your .map() callback isn't returning anything. You need to replace the braces with parentheses in the body of the callback in order to return your JSX:
{TeamsArray.map((element, key) => (
<View style={{ flex: 1, flexDirection: "row" }}>
<View>
<Text style={{ color: "#5DC1D3" }}>
{element.MembersList.nickName}
</Text>
<Text style={{ color: "#5DC1D3" }}>{element.Activity} </Text>
</View>
</View>;
))}
There's a few mistakes in your component, you'll have to fix those first before debugging.
// This is a component, not a hook, so use it like <GetFriendsRequest />
async function GetFriendsRequest() {
const [TeamsArray, updateTeamArray] = React.useState([]);
// This code was in the render loop
// put it inside a function so it doesn't run on every single render
const init = async () => {
const uid = await AsyncStorage.getItem("userID");
firestore()
.collection("Teams")
// Filter results
.where("uid", "==", uid)
.get()
.then((querySnapshot) => {
if (querySnapshot.empty) {
console.log("no documents found");
} else {
const results = [];
querySnapshot.forEach(async (doc) => {
let Teams = doc.data();
// Don't mutate react state, it should be treated as immutable
// TeamsArray.length = 0;
// This is an async function, but it's being
// called as if it were syncronous
// updateTeamArray((arr) => [...arr, Teams]);
results.push(Teams);
});
// Schedule a single state update
updateTeamArray([...results, ...TeamsArray]);
}
});
}
// Use an expression like this to debug
useEffect(() => {
// Log state every time it updates
console.log(TeamsArray);
}, [TeamsArray]);
useEffect(() => {
init();
}, []);
return (
<View>
{TeamsArray.map((element, key) => {
// Something has to be returned from this map
return <View style={{ flex: 1, flexDirection: "row" }}>
<View>
<Text style={{ color: "#5DC1D3" }}>
{element.MembersList.nickName}
</Text>
<Text style={{ color: "#5DC1D3" }}>{element.Activity} </Text>
</View>
</View>;
})}
</View>
);
};

How to Update state in return()?

I want to change the state when I get id of 5/6 or 7, after TouchableOpacity. Because I want to show the "Other Things" button one time whether id is 5/6 or 7.
export function HomePage({ navigation }) {
const [parentServiceCheck, setParentServiceCheck] = useState({ check: '0' });
return (
<View>
<FlatList numColumns={2} contentContainerStyle={{ margin: 7, flex: 1 }} keyExtractor={(item, index) => item.id} data={allService} renderItem={itemData => (
<View style={{ flexDirection: 'column', flex: 1 }}>
{
(itemData.item.id == 5 || itemData.item.id == 6 || itemData.item.id == 7) && parentServiceCheck.check == '0' ?
<TouchableOpacity onPress={() => pressHandler(itemData.item.id)} style={{ margin: 7 }}>
<Card titlebtn="Other Things" src={itemData.item.service_image} sty={{ height: 180, }} />
</TouchableOpacity>
// Now here I want to setParentServiceChildCheck({check: '1'}) when itemData.item.id has 5/6/7
:
<TouchableOpacity onPress={() => pressHandler(itemData.item.id)} style={{ margin: 7 }}>
<Card titlebtn={itemData.item.service_name} src={itemData.item.service_image} sty={{ height: 180, }} />
</TouchableOpacity>
}
</View>
)}
/>
</View>
)
}
You can't really update or execute any JS code like that. I would suggest to go through few training to learn about how things work in React JSX.
For now, if you want to update the state then you should be good to use it in useEffect as shown below
export default function HomePage({ navigation }) {
const [parentServiceCheck, setParentServiceCheck] = useState({ check: '0' });
useEffect(() => {
const hasValidId = allService.find(_hasValidId);
// This will get called only once after first render
// This will execute only when id's are 5, 6 or 7 which is your requirement
if (hasValidId) {
setParentServiceChildCheck({ check: '1' });
}
}, []);
const _hasValidId = itemData => {
const itemId = itemData?.item?.id;
const validItemIds = [5, 6, 7];
return validItemIds.includes(itemId);
};
const _renderItem = itemData => {
const itemId = itemData?.item?.id;
let content = null;
if (_hasValidId(itemData)) {
if (parentServiceCheck.check === '0') {
content = (
<TouchableOpacity onPress={() => pressHandler(itemId)} style={{ margin: 7 }}>
<Card titlebtn="Other Things" src={itemData.item.service_image} sty={{ height: 180 }} />
</TouchableOpacity>
);
} else {
content = (
<TouchableOpacity onPress={() => pressHandler(itemId)} style={{ margin: 7 }}>
<Card
titlebtn={itemData.item.service_name}
src={itemData.item.service_image}
sty={{ height: 180 }}
/>
</TouchableOpacity>
);
}
}
return <View style={{ flexDirection: 'column', flex: 1 }}>{content}</View>;
};
return (
<View>
<FlatList
numColumns={2}
contentContainerStyle={{ margin: 7, flex: 1 }}
keyExtractor={(item, index) => item.id}
data={allService}
renderItem={_renderItem}
/>
</View>
);
}
FYI, you might need to change few lines as the whole component code is not shared and I don't know about your business logic.
You should never update state in return / render function. It will make infinite rendering loop.

React native button within Card affects all other buttons in separate cards due to constant rendering

I am rendering separate cards in my render function by using data from an array. However I want a button within each Card to be pressed and only affect that exact Card.
this.state = {
isLiked: false,
feed: [{
username: ["stuff","here"],
caption: ["more","stuff"]
}]
}
toggleLike = () => {
this.setState({
isLiked = !this.state.isLiked
})
}
renderFeed = () => {
return this.state.feed.map((card, index) => {
return card.username.map((username, i) => {
if(card.caption[i])
return (
<View>
<TouchableHighlight
onPress={()=>this.toggleModal({caption:card.caption[i],username:card.username[i]})}
underlayColor="white">
<Card
key={`${i}_${index}`}
containerStyle={{borderRadius:10, marginRight:1, marginLeft:1,}}>
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'row'}}>
</View>
<View style={{flexDirection:'row'}}>
{this.state.isLiked ?(
<Avatar rounded icon={{name: 'heart-multiple-outline', type: 'material-community'}} overlayContainerStyle={{backgroundColor: '#ff4284',marginLeft: 5}} reverse size="small" onPress={()=> this.toggleLike()}/>
) : (
<Avatar
rounded
icon={{ name:'heart-multiple-outline', type:'material-community', color: '#ff4284'}}
overlayContainerStyle={{marginLeft:5}}
reverse
size='small'
onPress={()=> this.toggleLike()}/>
)}
</View>
</View>
<View style={{flexDirection:'row'}}>
<Text style={{fontFamily: 'MontserratB', color:'#bf00b9', marginTop:10}} key={username}>{username}</Text>
<Text style={{fontFamily:'Montserrat', marginTop:10}} key={card.caption}>{card.caption[i]}</Text>
</Card>
</TouchableHighlight>
</View>
);
return <React.Fragment />;
});
})
}
render(){
{this.renderFeed()}
}
Is there any way I can make it so that each card's like button is independent?
Here is an expo snack so you can see what I mean. https://snack.expo.io/#sooper_fly/demoforlikes
I build expo snack, Something like this:
https://snack.expo.io/#djalik/demoforlikes
you can improve your code and make card/item component and set the data over props.
Recommend: Work with FlatList

passing data into a modal

I'm trying to pass some data from container to modal, and i've done this. it got error undefined is not an object evaluating (evaluating _this.props.status) is there anything i did worng? what should i call in props
these are my codes
container.js
buildPanel(index, item) {
let panel = [];
let keys = DBkeys['Requests'].MyRequest;
let status = item[keys['status']];
panel.push(<View style={{ position: 'absolute', right: 0, bottom: 0, padding: normalize(5), alignItems: 'center' }} key={'status'}>
<TouchableOpacity onPress={this.handleShowModal()}>
<Icon name={img.itemStatus[status].name} type={img.itemStatus[status].type} color={img.itemStatus[status].color} size={normalize(38)} />
</TouchableOpacity>
</View>);
return panel;
}
<View style={[styles.panelContainer, status === 'success' ? {} : { backgroundColor: color.white }]}>
<FlatList
showsVerticalScrollIndicator={false}
progressViewOffset={-10}
refreshing={this.state.refreshing}
onRefresh={this.onRefresh.bind(this)}
onMomentumScrollEnd={(event) => event.nativeEvent.contentOffset.y === 0 ? this.onRefresh() : null}
data={content}
renderItem={({ item }) => item}
keyExtractor={(item, key) => key.toString()}
/>
</View>
<IconModal visible={this.state.modalVisible} close={this.handleDismissModal} status='test' desc='test' />
IconModal.js
const IconModal = (props) => {
return(
<Modal
isVisible={props.visible}
onBackdropPress={props.close}
>
<View style={styles.dialogBox}>
<View style={styles.icon}>
<Icon></Icon>
</View>
<View style={styles.text}>
<Text style={styles.status}>{this.props.status}</Text>
<Text>{this.props.desc}</Text>
</View>
<TouchableOpacity onPress={props.close}>
<View>
<Text style={styles.buttonText}>GOT IT</Text>
</View>
</TouchableOpacity>
</View>
</Modal>
)
}
IconModal.propTypes ={
visible: PropTypes.bool.isRequired,
close: PropTypes.func,
}
Use double quotes while passing string to the component. like status="test" desc="test" instead of status='test' desc='test' . and instead of this.props.status use props.status. same with this.props.desc
Remove the this keyword. It should be just props.status and props.desc

How to reload Flatlist react native?

I have a rendered list and I would like it when a change in status is generated the entire FlatList is recharged
what I have is a search engine and I want that when it brings the new data the FlatList will refresh itself with the new information
I need that every time you enter a letter in the search engine the FlatList will recharge
async buscar(buscar) {
this.setState({refreshing: true});
const coins = await ajax.searchProd(buscar);
this.setState({coins});
console.log(coins);
this.setState({refreshing: false});
}
render() {
return (
<View style={styles.container}>
<Image style={styles.logoHeader} source={require('../../public/images/productos.png')}/>
<View style={styles.containerSearch}>
<TextInput
style={styles.inputBuscar}
placeholder={'Buscar Productos'}
underlineColorAndroid={"transparent"}
onChangeText={(buscar) => {
this.setState({buscar: buscar});
this.buscar(this.state.buscar);
console.log(this.state.buscar);
}}
/>
<Image style={styles.imageSearch} source={require('../../public/images/search.png')}/>
</View>
<View style={styles.containerPro}>
<FlatList
extraData={this.state.coins}
data={this.state.coins}
keyExtractor={(item) => item.id.toString()}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh}
/>
}
renderItem={({item}) => {
let url = 'http://laeconomiadelsur.com/upload/' + item.foto;
const tableData = [
[<View>
<Image source={{uri: url}} style={{
width: 50,
height: 70,
}}/>
</View>,
],
[<View style={styles.cellIcons}>
<Text
style={styles.textCells}>{item.nombre}</Text>
<Text
style={styles.textCellsDescription}>{item.descripcion}</Text>
<Text
style={styles.textCellsPrecio}>{numeral(item.precio).format('$0,0')}</Text>
</View>,
],
[<View>
<Text style={styles.cantidad1}>seleccionar: </Text>
<View>
<NumericInput
onChange={(value) => {
let total = value * item.precio;
console.log(value);
console.log(total)
}}
totalWidth={calcSize(250)}
totalHeight={calcSize(70)}
minValue={0}
iconSize={15}
step={1}
sepratorWidth={0}
borderColor={'transparent'}
inputStyle={{
backgroundColor: 'rgb(252,226,227)',
borderTopColor: 'rgb(226,0,30)',
borderBottomColor: 'rgb(226,0,30)',
borderWidth: 1,
fontFamily: "NeutraText-BookSC",
fontSize: 17
}}
containerStyle={{
borderWidth: 1,
borderColor: 'rgb(226,0,30)',
backgroundColor: 'transparent',
}}
rounded
textColor='#000000'
rightButtonBackgroundColor={'rgb(235,209,210)'}
leftButtonBackgroundColor={'rgb(235,209,210)'}
/>
</View>
<Text style={styles.cantidad}>cantidad</Text>
</View>,]
];
return (
<View style={{flex: 1}} key={item.id}>
<Table style={styles.table} borderStyle={{borderWidth: 2, borderColor: 'white'}}
key={item.id}>
<Cols data={tableData} flexArr={[1, 2, 2]} style={styles.cells}
key={item.id}/>
</Table>
</View>
);
}}
/>
</View>
</View>
);
<TextInput
style={styles.inputBuscar}
placeholder={'Buscar Productos'}
underlineColorAndroid={"transparent"}
onChangeText={(buscar) => {
/* Updated buscar value won't be available in next line instantly
* just after the setState. So, better set buscar State in
* this.buscar() Function.
*/
/* this.setState({buscar: buscar}); Move to buscar Function*/
this.buscar(buscar).then(()=>{
console.log(this.state.buscar);
}).catch((e)=> console.log("Error: ",e))
}}
/>
An Async function always returns a promise object. So, while calling buscar function you should handle the promise.
async buscar(buscar) {
this.setState({
refreshing: true,
buscar: buscar,
});
const coins = await ajax.searchProd(buscar);
console.log(coins);
this.setState({
coins: conins,
refreshing: false
});
}
In Flatlist ExtraData property should contain the this.state
extraData={this.state}