I’m trying to keep the history of each time a list is selected and store the name of the list and the time it was selected. I used a global array to store this but I’m not sure how to properly syntax it without receiving errors.
Here is where the array is defined.
var listName = truncate(title) + ' '
global.historyData.push({createID, listName, currentDate})
console.log(global.historyData);
Stores an ID, list name and current date at that time.
This is a different page that displays the history of the list. I want it to keep the history even when the user reloads the app, hence the async storage.
Here is the second-page code.
global.historyData = useState([]);
const ShoppingHistoryCard = (state, {route}) => {
React.useEffect(() => {
const fetchHistory = async () => {
const response = await getItem('{global.historyData}');
safeDispatch({
type: 'RESTORE_HISTORY',
payload: {
global.historyData: response === null ? [] : response
}
});
};
fetchHistory();
}, [safeDispatch]);
React.useEffect(() => {
const saveHistory = async () => {
await setItem('global.historyData', state?.global.historyData ?? []);
};
if (state.isRestoringHistory === false) {
saveHistory();
}
}, [state.global.historyData, state.isRestoringHistory]);
const safeDispatch = React.useCallback((...args) => {
if (hasMounted.current === true) {
dispatch(...args);
}
}, []);
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
console.log('Refreshed!');
});
return unsubscribe;
}, [navigation]);
And where the array is irrerated through to display the items.
const renderElements = () => {
let jsx = [];
let varElements = [];
global.historyData.forEach((item) => {
if (varElements.length > 0) {
jsx.push(<View style={{flexDirection: 'row'}}>{varElements}</View>);
}
varElements = [];
jsx.push(<Text>{item.listName}{item.currentDate}</Text>);
}
);
return jsx;
};
return(
<View>
<Text style={styles.title}>Shopping List History</Text>
<View style={styles.section}>
<View style={{width:170}}>
{renderElements()}
</View>
</View>
</View>
);
}