How to get AsyncStorage key name from FlatList item to delete? - react-native

I am generating a random key name for AsyncStorage each time user saves an item. These are then displayed in FlatList (using SwipeListView library for swipe to delete button). Now if I call await AsyncStorage.removeItem(key); when the user taps "Delete", I presume the item will just disappear from the list. What I'm completely lost on is how I am supposed to get my random key name? Struggling to find much on FlatList and AsyncStorage, not sure what good practice is.
FlatList:
export default class RecentMealsScreen extends Component {
constructor() {
super();
this.state={
meals: []
}
}
componentDidMount() {
this.getAllMeals();
}
getAllMeals = async () => {
try {
const data = [];
let keys = await AsyncStorage.getAllKeys();
for (let inKey of keys) {
let obj = await AsyncStorage.getItem(inKey);
obj = JSON.parse(obj);
data.push(obj);
}
this.setState({
meals: data
})
} catch (error) {
console.log("Error saving all meals. Error: " + error)
}
}
renderHiddenItem = () => (
<View style={styles.rowBack}>
<View style={[styles.backRightBtn, styles.backRightBtnRight]}>
<Text style={styles.backTextWhite}>Delete</Text>
</View>
</View>
);
deleteMeal = async (key) => {
try {
await AsyncStorage.removeItem(key);
} catch (error) {
console.log('Error deleting Meal: ' + error)
}
}
// Get Meal IDs and display them in list
render() {
return (
<View style={styles.container}>
<SwipeListView
data={this.state.meals}
renderItem={ ({item}) =>
<View style={styles.container}>
<Meal
image = {item.image}
order={item.orderName}
company={item.companyName}
price={item.price}
dateTime={item.dateTime}
notes={item.notes}
rating = {item.rating}
/>
</View>
}
disableRightSwipe
renderHiddenItem={this.renderHiddenItem}
rightOpenValue={-Dimensions.get('window').width}
useNativeDriver={false}
onSwipeValueChange={this.deleteMeal()}
/>
</View>
);
}
}
Save Logic:
saveMeal = async () => {
try {
let meal = {
image: this.state.imageSource,
orderName: this.state.orderText,
companyName: this.state.selectedCompany,
price: this.state.priceText,
dateTime: this.state.dateTimeText,
notes: this.state.notesTextField,
rating: this.state.starCount
};
const ID = await Random.getRandomBytesAsync(16);
await AsyncStorage.setItem(ID.toString(), JSON.stringify(meal)).then(() => {
// Redirect to new screen
Actions.recentMeals();
})
} catch (error) {
console.log("Save Meal error: " + error)
}
}

Related

react native: Rendering an array of strings and numbers doesn't work

In the react native app I'm retrieving some data from my backend and then want to display it to the app user:
when I log the data I can see that I receive it and stored it properly in the state as an object:
// console.log("received the data: ", this.state.data) ->
received the data: Object {
"a": 48,
"b": "2021-03-29T17:11:51Z",
"c": "",
"d": false
}
But when I try to render that in my view, the screen simply stays empty (no error message):
render() {
// let me check, if the data is really there
Object.entries(this.state.data).map(([key, value]) => {
console.log("key: ", key, "- value: ", value)
})
// output:
// key: a - value: 48,
// key: b - value: 2021-03-29T17:11:51Z,
// key: c - value: ,
// key:d - value: false
return (
<View>
{Object.entries(this.state.data).map(([key, value]) => {
return <View key={key}><Text>{value}</Text></View>
})}
</View>
)
}
I also tried this, but still I receive an empty screen:
render() {
return (
{ this.state.data.map((items, index) => {
return (
<ul key={index}>
{Object.keys(items).map((key) => {
return (
<li key={key + index}>{key}:{items[key]}</li>
)
})}
</ul>
)
})}
)
}
Edit: The full component:
import React from 'react'
import { View, Text } from 'react-native'
import axios from 'axios';
class SuccessScreen extends React.Component {
baseURL = "https://my-backend-server-URL.com/data"
state = {
data: {},
}
componentDidMount() {
this.startGetData();
}
startGetData = () => {
axios.get(this.baseUrl)
.then(response => {
console.log("got the data: ", response.data)
this.state.data = response.data;
})
.catch(function (err) {
//handle error
console.log("error getting data: ", err.message)
return {
type: "REGISTER_USER_FAILED",
payload: null
}
});
};
render() {
console.log("This log will show up")
return (
<View>
{this.state.vehicleData && Object.entries(this.state.vehicleData).map(([key, value]) => {
console.log("this log never shows up... key: ", key) // these logs don't not show up
return <View key={key}><Text>{value}</Text></View>
})}
</View>
)
}
}
export default SuccessScreen;
Wait for data to be defined, Try this:
return (
<View>
{this.state.data && Object.entries(this.state.data).map(([key, value]) => {
return <View key={key}><Text>{value}</Text></View>
})}
</View>
Edit:
Don't mutate this.state.data = response.data that way, use the setState:
this.setState({ data: response.data });
https://reactjs.org/docs/faq-state.html#what-does-setstate-do

Why is AsyncStorage getAllKeys not returning null? Have multiple views, want to render based on if data found, deleted all keys

I have a boolean called isDataReady stored in the state. If I find keys via AsyncStorage, I set it true and display a list of data. If nothing is found then I want to render a different view. My data is displaying fine but with everything deletef, I can't get my intro screen to display. Its because AsyncStorage is never null despite their being no keys. What am I doing wrong?
Code (view related code removed for clarity)
constructor() {
super();
this.state={
meals: [],
isDataReady: false,
}
}
componentDidMount() {
this.getAllMeals();
}
getAllMeals = async () => {
try {
const data = [];
let keys = await AsyncStorage.getAllKeys();
// await AsyncStorage.multiRemove(keys);
if (keys !== null) {
for (let inKey of keys) {
let obj = await AsyncStorage.getItem(inKey);
obj = JSON.parse(obj);
obj["key"] = inKey;
data.push(obj);
}
this.setState({
meals: data,
isDataReady: true
})
} else {
this.setState({
isDataReady: false
})
}
} catch (error) {
console.log("Error saving all meals. Error: " + error)
}
}
render() {
if (this.state.isDataReady === true) {
return (
<View style={styles.container}>
</View>
);
} else if (this.state.isDataReady === false) {
return (
<ScrollView>
<View style={styles.container}>
</View>
</ScrollView>
);
}
}
}
I change the if statement to if (keys.length !== 0), always returns array so its never null.

To save the data onpress of item in a asycstorage in react native

I'm trying to display the time zone in another screen when an item is pressed in previous flatlist. My data is coming from autocomplete when I'm selecting it is displayed in flatlist.
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
data={autotime.length === 1 && comp(query, autotime[0].name) ? [] : autotime}
defaultValue={this.state.timeZone}
onChangeText={text => this.setState({ query: text })}
placeholder="Enter Location"
renderItem={({ name, release_date }) => (
<TouchableOpacity onPress={() => this.setState({ query: name,timezoneArray:autotime[0].timezones })}>
<Text style={styles.itemText}>
{name}
</Text>
</TouchableOpacity>
)}
/>
<View style={styles.descriptionContainer}>
{autotime.length > 0 ? (
<FlatList
style={{flex:1}}
data={this.state.timezoneArray}
renderItem={({ item }) => <TimeZoneItem text={item} />}
/>
) : (
<Text style={styles.infoText}>Enter Location</Text>
)}
I want that when I press the items of flatlist it is displayed on another page.
Picture below shows what I have made:
My Data base helper class is:
export const SaveItem = (key, value) => {
AsyncStorage.setItem(key, value);
};
export const ReadItem = async (key) => {
try {
var result = await AsyncStorage.getItem(key);
return result;
} catch (e) {
return e;
}
};
export function MultiRead(key, onResponse, onFailure) {
try {
AsyncStorage.multiGet(key).then(
(values) => {
let responseMap = new Map();
values.map((result, i, data) => {
let key = data[i][0];
let value = data[i][1];
responseMap.set(key, value);
});
onResponse(responseMap)
});
} catch (error) {
onFailure(error);
}
};
export async function DeleteItem(key) {
try {
await AsyncStorage.removeItem(key);
return true;
}
catch (exception) {
return false;
}
}
and here i have added my code to save
handleTimezone = (text) => {
this.setState({ TimeZoneItem: text })
}
newData.TimeZoneItem = this.state.TimeZoneItem
this.setState({
TimeZoneItem: '',
})
ReadItem('timeData').then((result) => {
let temp = []
if (result != null) {
temp = JSON.parse(result)
} else {
temp = []
}
temp.push(newData)
SaveItem('timeData', JSON.stringify(temp))
console.log(`New Data: ${JSON.stringify(temp)}`)
}).catch((e) => {
})
}
<FlatList
style={{flex:1}}
data={this.state.timezoneArray}
renderItem={({ item }) => (
<TouchableOpacity>
<TimeZoneItem text={item} onPress={() => this.props.onPress()}
value={this.state.TimeZoneItem}
/>
</TouchableOpacity>)}
You'll need an array to saved all the saved items.
for example
state = {
saved: []
};
On press the time zone item, get the values from state, add the new item to the array and save the array to async storage using JSON.stringify()
onSave = item => {
const { saved } = this.state;
const newItems = [...saved, item];
this.setState({
saved: newItems
});
const items = JSON.stringify(newItems);
SaveItem("saved", items)
.then(res => {
console.warn("saved", res);
})
.catch(e => console.warn(e));
};
Then in your other screen get the items in using your ReadItem function like.
state = {
saved: []
};
componentDidMount = () => {
ReadItem("saved")
.then(res => {
if (res) {
const saved = JSON.parse(res);
this.setState({
saved: saved
});
}
})
.catch(e => console.warn(e));
};
Working Demo

React Native Flat List doesn't call onEndReached handler after two successful calls

I implement a very simple list that calls a server that returns a page containing books.Each book has a title, author, id, numberOfPages, and price). I use a Flat List in order to have infinite scrolling and it does its job very well two times in a row (it loads the first three pages) but later it doesn't trigger the handler anymore.
Initially it worked very well by fetching all available pages, but it stopped working properly after I added that extra check in local storage. If a page is available in local storage and it has been there no longer than 5 seconds I don't fetch the data from the server, instead I use the page that is cached. Of course, if there is no available page or it is too old I fetch it from the server and after I save it in local storage.(Something went wrong after adding this behavior related to local storage.)
Here is my component:
export class BooksList extends Component {
constructor(props) {
super(props);
this.state = {
pageNumber: 0
};
}
async storePage(page, currentTime) {
try {
page.currentTime = currentTime;
await AsyncStorage.setItem(`page${page.page}`, JSON.stringify(page));
} catch (error) {
console.log(error);
}
}
subscribeToStore = () => {
const { store } = this.props;
this.unsubsribe = store.subscribe(() => {
try {
const { isLoading, page, issue } = store.getState().books;
if (!issue && !isLoading && page) {
this.setState({
isLoading,
books: (this.state.books ?
this.state.books.concat(page.content) :
page.content),
issue
}, () => this.storePage(page, new Date()));
}
} catch (error) {
console.log(error);
}
});
}
componentDidMount() {
this.subscribeToStore();
// this.getBooks();
this.loadNextPage();
}
componentWillUnmount() {
this.unsubsribe();
}
loadNextPage = () => {
this.setState({ pageNumber: this.state.pageNumber + 1 },
async () => {
let localPage = await AsyncStorage.getItem(`page${this.state.pageNumber}`);
let pageParsed = JSON.parse(localPage);
if (localPage && (new Date().getTime() - localPage.currentTime) < 5000) {
this.setState({
books: (
this.state.books ?
this.state.books.concat(pageParsed.content) :
page.content),
isLoading: false,
issue: null
});
} else {
const { token, store } = this.props;
store.dispatch(fetchBooks(token, this.state.pageNumber));
}
});
}
render() {
const { isLoading, issue, books } = this.state;
return (
<View style={{ flex: 1 }}>
<ActivityIndicator animating={isLoading} size='large' />
{issue && <Text>issue</Text>}
{books && <FlatList
data={books}
keyExtractor={book => book.id.toString()}
renderItem={this.renderItem}
renderItem={({ item }) => (
<BookView key={item.id} title={item.title} author={item.author}
pagesNumber={item.pagesNumber} />
)}
onEndReachedThreshold={0}
onEndReached={this.loadNextPage}
/>}
</View>
)
}
}
In the beginning the pageNumber available in the state of the component is 0, so the first time when I load the first page from the server it will be incremented before the rest call.
And here is the action fetchBooks(token, pageNumber):
export const fetchBooks = (token, pageNumber) => dispatch => {
dispatch({ type: LOAD_STARTED });
fetch(`${httpApiUrl}/books?pageNumber=${pageNumber}`, {
headers: {
'Authorization': token
}
})
.then(page => page.json())
.then(pageJson => dispatch({ type: LOAD_SUCCEDED, payload: pageJson }))
.catch(issue => dispatch({ type: LOAD_FAILED, issue }));
}
Thank you!

How to access a row using FlatList keyExtractor in react-native

Is there any way to access a row using key, set using keyExtractor in FlatList.
I using FlatList inorder to populate by data, i need to get a row separately using it's key, inorder to update that row without re-render the entire view.
on componentWillMount i populated datalist array using an api call.
dummy array look this
[{id:"Usr01",title:"Name1"},{id:"Usr02",title:"Name2"},...]
while press on any row i get it's id, i need to access that row using it's key.
let dataitem = this.state.datalist[id];
while i console dataitem i get undefined
i set id as the key in keyExtractor, is there any way to do the same.
My code look like this
FlatListScreen.js
export default class FlatListScreen extends Component {
constructor(props)
{
super(props);
this.state={
datalist: [],
}
}
componentWillMount() {
ApiHandler.getlistitem('All').then(response =>{
this.setState({datalist: response});
});
}
_keyExtractor = (item, index) => item.id;
_onPressItem = (id) => {
let dataitem = this.state.datalist[id];
const { name } = dataitem
const newPost = {
...dataitem,
name: name+"01"
}
this.setState({
datalist: {
...this.state.datalist,
[id]: newPost
}
})
};
_renderItem ({ item }) {
return (
<MyListItem
id={item.id}
onPressItem={this._onPressItem}
title={item.title}
/>
)
}
render() {
return (
<FlatList
data={this.state.datalist}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
);
}
}
}
MyListItem.js
export default class MyListItem extends Component {
constructor(props) {
super(props)
this.state = {
title: '',
id: ''
}
}
componentWillMount() {
const { title, id } = this.props
this.setState({ title, id })
}
componentWillReceiveProps(nextProps) {
const { title, id } = nextProps
this.setState({ title, id })
}
shouldComponentUpdate(nextProps, nextState) {
const { title} = nextState
const { title: oldTitle } = this.state
return title !== oldTitle
}
render() {
return (
<View>
<TouchableOpacity onPress={() =>this.props.onPressItem({id:this.state.id})}>
<View>
<Text>
{this.props.title}
</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
I think changing
onPressItem({id:this.state.id});
to
onPressItem(this.state.id); in your child component
OR
_onPressItem = (id) => { }
to
_onPressItem = ({id}) => { }
in your parent component will solve the issue.
As you are sending it as an object from child to parent and you can access it like this also
let dataitem = this.state.datalist[id.id];