To automatically update the "7 minutes ago" text as time passes, you would need to implement a mechanism to re-render the component at regular intervals. One common method for achieving this in React Native is using the setInterval function. In this case, you'll create a timer that triggers a re-render to refresh the "time ago" text periodically.
Below is an example of how you can achieve this:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { Card, Chip } from 'react-native-paper';
export type Props = {
addMessage: (message: string) => void,
data: FoodData,
theme: MD3Theme,
};
type State = {
expanded: boolean,
timeAgo: string
};
const getTimeAgo = (date: Date): string => {
// Your existing getTimeAgo implementation
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - new Date(date).getTime()) / 1000);
if (diffInSeconds < 60) return `${diffInSeconds} seconds ago`;
const diffInMinutes = Math.floor(diffInSeconds / 60);
if (diffInMinutes < 60) return `${diffInMinutes} minutes ago`;
const diffInHours = Math.floor(diffInMinutes / 60);
if (diffInHours < 24) return `${diffInHours} hours ago`;
const diffInDays = Math.floor(diffInHours / 24);
return `${diffInDays} days ago`;
};
class FoodPost extends Component<Props, State> {
interval: NodeJS.Timeout | null = null;
constructor(props: Props) {
super(props);
this.state = {
expanded: false,
timeAgo: getTimeAgo(props.data.date)
};
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({ timeAgo: getTimeAgo(this.props.data.date) });
}, 60000); // Update every minute
}
componentWillUnmount() {
if (this.interval) {
clearInterval(this.interval);
}
}
handlePress = () => {
console.log("pressed lol");
// this.setState(prevState => ({ expanded: !prevState.expanded }));
}
render() {
const { addMessage, data, theme, ...rest } = this.props;
const { timeAgo } = this.state;
return (
<View style={{ margin: 8 }}>
<Card mode="contained" style={{ backgroundColor: theme.colors.inverseOnSurface }} onPress={this.handlePress}>
<Card.Title titleStyle={{ fontWeight: 'bold', paddingTop: 8 }} titleVariant="titleLarge" titleNumberOfLines={2} title={data.location} subtitle={timeAgo} rightStyle={{ paddingRight: 20 }}
right={(props) => <Text>< 3 miles</Text>} />
{/* Show chips */}
<Card.Content style={{ paddingTop: 8, flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
{<Chip compact onPress={() => addMessage("This item requires you to leave campus or use transportation")} icon="car">Off-Campus</Chip>}
{<Chip compact onPress={() => addMessage("Bring your phone (fill out form, show voucher, etc.)")} icon="cellphone">Need Phone</Chip>}
{<Chip compact onPress={() => addMessage("Food is behind locked doors or in a private event")} icon="door-sliding-lock">Entry Needed</Chip>}
</Card.Content>
{/* Body */}
<Card.Content style={{ paddingTop: 8 }}>
<Text variant="bodyLarge">{data.details}</Text>
</Card.Content>
</Card>
</View>
);
}
shouldComponentUpdate(nextProps: Readonly<Props>, nextState: Readonly<State>, nextContext: any): boolean {
console.log(nextProps);
return this.state.timeAgo !== nextState.timeAgo;
}
}
export default FoodPost;
Key Points:
- State for Time Ago: I added
timeAgo to the component state to store the string representing the elapsed time.
- Timer Setup:
setInterval is set up in componentDidMount to update the timeAgo state every minute.
- Cleanup Timer:
clearInterval is called in componentWillUnmount to avoid memory leaks.
- Conditional Re-render:
shouldComponentUpdate method is updated to compare the old and new timeAgo values, thereby only re-rendering the component when the timeAgo state changes.
This approach ensures that the component will update its "time ago" display every minute, keeping the information accurate for the user.