How I can resolve this : Warning: Encountered two children with the same key, `%s` - react-native

I am new to react-native and this is not me who program this app.
Could someone help me to fix this error, I think its the flatlist who cause this because it happen only I load the page or search something on the list. I know there is a lot a question about this error but I don't find a solution for me.
Warning: Encountered two children with the same key,%s. Keys should be unique so that components maintain their identity across updates.
ContactScreen.js
import React from 'react';
import { Button, View, FlatList, Alert, StyleSheet, KeyboardAvoidingView } from 'react-native';
import { ListItem, SearchBar } from 'react-native-elements';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Contacts } from 'expo';
import * as Api from '../rest/api';
import theme from '../styles/theme.style';
import { Contact, ContactType } from '../models/Contact';
class ContactsScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: "Contacts",
headerRight: (
<Button
onPress={() => navigation.popToTop()}
title="Déconnexion"
/>
),
}
};
constructor(props) {
super(props);
this.state = {
contacts: [],
search: '',
isFetching: false,
display_contacts: []
}
}
async componentDidMount() {
this.getContactsAsync();
}
async getContactsAsync() {
const permission = await Expo.Permissions.askAsync(Expo.Permissions.CONTACTS);
if (permission.status !== 'granted') { return; }
const contacts = await Contacts.getContactsAsync({
fields: [
Contacts.PHONE_NUMBERS,
Contacts.EMAILS,
Contacts.IMAGE
],
pageSize: 100,
pageOffset: 0,
});
const listContacts = [];
if (contacts.total > 0) {
for(var i in contacts.data) {
let contact = contacts.data[i];
let id = contact.id;
let first_name = contact.firstName;
let middle_name = contact.middleName;
let last_name = contact.lastName;
let email = "";
if ("emails" in contact && contact.emails.length > 0) {
email = contact.emails[0].email;
}
let phone = "";
if ("phoneNumbers" in contact && contact.phoneNumbers.length > 0) {
phone = contact.phoneNumbers[0].number;
}
listContacts.push(new Contact(id, first_name, middle_name, last_name, email, phone, ContactType.UP));
}
}
const soemanContacts = await Api.getContacts();
if (soemanContacts.length > 0) {
for(var i in soemanContacts) {
let contact = soemanContacts[i];
let id = contact.contact_id.toString();
let first_name = contact.contact_first_name
let last_name = contact.contact_last_name;
let email = contact.contact_email;
let phone = contact.contact_phone.toString();
listContacts.push(new Contact(id, first_name, "", last_name, email, phone, ContactType.DOWN));
}
}
listContacts.sort((a, b) => a.name.localeCompare(b.name));
this.setState({contacts: listContacts});
this.setState({ isFetching: false });
this.updateSearch(null);
}
async addContactAsync(c) {
const contact = {
[Contacts.Fields.FirstName]: c.firstName,
[Contacts.Fields.LastName]: c.lastName,
[Contacts.Fields.phoneNumbers]: [
{
'number': c.phone
},
],
[Contacts.Fields.Emails]: [
{
'email': c.email
}
]
}
const contactId = await Contacts.addContactAsync(contact);
}
onRefresh() {
this.setState({ isFetching: true }, function() { this.getContactsAsync() });
}
updateSearch = search => {
this.setState({ search });
if(!search) {
this.setState({display_contacts: this.state.contacts});
}
else {
const res = this.state.contacts.filter(contact => contact.name.toLowerCase().includes(search.toLowerCase()));
console.log(res);
this.setState({display_contacts: res});
console.log("contact display "+ this.state.display_contacts);
}
};
toggleContact(contact) {
switch(contact.type) {
case ContactType.SYNC:
break;
case ContactType.DOWN:
this.addContactAsync(contact);
break;
case ContactType.UP:
Api.addContact(contact);
break;
}
/*Alert.alert(
'Synchronisé',
contact.name + 'est déjà synchronisé'
);*/
}
renderSeparator = () => (
<View style={{ height: 0.5, backgroundColor: 'grey', marginLeft: 0 }} />
)
render() {
return (
<View style={{ flex: 1 }}>
<KeyboardAvoidingView style={{ justifyContent: 'flex-end' }} behavior="padding" enabled>
<SearchBar
platform="default"
lightTheme={true}
containerStyle={styles.searchBar}
inputStyle={styles.textInput}
placeholder="Type Here..."
onChangeText={this.updateSearch}
value={this.state.search}
clearIcon
/>
<FlatList
data={this.state.display_contacts}
onRefresh={() => this.onRefresh()}
refreshing={this.state.isFetching}
renderItem={this.renderItem}
keyExtractor={contact => contact.id}
ItemSeparatorComponent={this.renderSeparator}
ListEmptyComponent={this.renderEmptyContainer()}
/>
</KeyboardAvoidingView>
</View>
);
}
renderItem = (item) => {
const contact = item.item;
let icon_name = '';
let icon_color = 'black';
switch(contact.type) {
case ContactType.SYNC:
icon_name = 'ios-done-all';
icon_color = 'green';
break;
case ContactType.DOWN:
icon_name = 'ios-arrow-down';
break;
case ContactType.UP:
icon_name = 'ios-arrow-up';
break;
}
return (
<ListItem
onPress={ () => this.toggleContact(contact) }
roundAvatar
title={contact.name}
subtitle={contact.phone}
//avatar={{ uri: item.avatar }}
containerStyle={{ borderBottomWidth: 0 }}
rightIcon={<Ionicons name={icon_name} size={20} color={icon_color}/>}
/>
);
}
renderEmptyContainer() {
return (
<View>
</View>
)
}
}
const styles = StyleSheet.create({
searchBar: {
backgroundColor: theme.PRIMARY_COLOR
},
textInput: {
backgroundColor: theme.PRIMARY_COLOR,
color: 'white'
}
});
export default ContactsScreen;
I use react-native and expo for this application.

Just do this in you flatlist
keyExtractor={(item, index) => String(index)}

I think that your some of contact.id's are same. So you can get this warning. If you set the index number of the list in FlatList, you can't show this.
keyExtractor={(contact, index) => String(index)}

Don't build keys using the index on the fly. If you want to build keys, you should do it BEFORE render if possible.
If your contacts have a guaranteed unique id, you should use that. If they do not, you should build a key before your data is in the view using a function that produces unique keys
Example code:
// Math.random should be unique because of its seeding algorithm.
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
const keyGenerator = () => '_' + Math.random().toString(36).substr(2, 9)
// in component
key={contact.key}

Just do this in your Flatlist
keyExtractor={(id) => { id.toString(); }}

I got same error and I fixed in this case:
do not code in this way (using async) - this will repeat render many times per item (I don't know why)
Stub_Func = async () => {
const status = await Ask_Permission(...);
if(status) {
const result = await Get_Result(...);
this.setState({data: result});
}
}
componentDidMount() {
this.Stub_Func();
}
try something like this (using then):
Stub_Func = () => {
Ask_Permission(...).then(status=> {
if(status) {
Get_Result(...).then(result=> {
this.setState({data:result});
}).catch(err => {
throw(err);
});
}
}).catch(err => {
throw(err)
});
}
componentDidMount() {
this.Stub_Func();
}

Related

FlatList in ReactNative does not update/re-render when its data changes

Hej, I advanced my FlatList in React Native with
a) inbox/archive views
and b) with standard filter functionalities.
It's working somehow, but is not production ready!
Can someone please check this (I think well-organized) code and tell me where I do what wrong?
What is not working:
a) FlatList does not always re-render/update when the stream state, which is its data prop, changes
b) FlatList does not remove an item immediately when I archive/unarchive via swipe functionality. I have to manually change the view to see ...
c) FlatList does not directly apply the filter on state, I have to click twice to make it happen ...
//React
import { View, StyleSheet, Pressable, Animated, FlatList } from "react-native";
import { useCallback, useContext, useEffect, useState, useMemo } from "react";
//Internal
import SelectBtn from "./SelectBtn";
import SessionComponent from "./SessionComponent";
import LoadingOverlay from "../notification/LoadingOverlay";
import { SessionsContext } from "../../store/context-reducer/sessionsContext";
//External
import { Ionicons } from "#expo/vector-icons";
import { useNavigation } from "#react-navigation/native";
import { database, auth } from "../../firebase";
import { ref, onValue, remove, update } from "firebase/database";
function SessionStream() {
const navigation = useNavigation();
const sessionsCtx = useContext(SessionsContext);
const currentSessions = sessionsCtx.sessions;
const [isFetching, setIsFetching] = useState(true);
const [stream, setStream] = useState([]);
const [inbox, setInbox] = useState([]);
const [archive, setArchive] = useState([]);
const [filter, setFilter] = useState([]);
const sessionList = ["Sessions", "Archive"];
const sortList = ["ABC", "CBA", "Latest Date", "Earliest Date"];
useEffect(() => {
//Fetches all sessions from the database
async function getSessions() {
setIsFetching(true);
const uid = auth.currentUser.uid;
const sessionsRef = ref(database, "users/" + uid + "/sessions/");
try {
onValue(sessionsRef, async (snapshot) => {
const response = await snapshot.val();
if (response !== null) {
const responseObj = Object.entries(response);
const sessionsData = responseObj.map((item) => {
return {
id: item[1].id,
title: item[1].title,
laps: item[1].laps,
endTime: item[1].endTime,
note: item[1].note,
identifier: item[1].identifier,
date: item[1].date,
smed: item[1].smed,
externalRatio: item[1].externalRatio,
internalRatio: item[1].internalRatio,
untrackedRatio: item[1].untrackedRatio,
archived: item[1].archived,
};
});
sessionsCtx.setSession(sessionsData);
setIsFetching(false);
} else {
sessionsCtx.setSession([]);
setIsFetching(false);
}
});
} catch (err) {
alert(err.message);
setIsFetching(false);
}
}
getSessions();
}, []);
useEffect(() => {
//Sorts sessions into archived and unarchived
setInbox(
currentSessions.filter((session) => {
return session.archived === false || session.archived === undefined;
})
);
setArchive(
currentSessions.filter((session) => {
return session.archived === true;
})
);
}, [currentSessions, archiveHandler, unArchiveHandler, sessionsCtx, stream]);
if (isFetching) {
setTimeout(() => {
return <LoadingOverlay />;
}, 5000);
}
const onPressHandler = useCallback(
//Callback to open the session
(item) => {
navigation.navigate("Detail", {
sessionID: item.id,
});
},
[onPressHandler]
);
const rightSwipeActions = useCallback(
//Swipe actions for the session list
(item, swipeAnimatedValue) => {
return (
<View
style={{
flexDirection: "row",
width: 168,
height: 132,
}}
>
{item.archived === false ? (
<Pressable
onPress={archiveHandler.bind(this, item)}
style={({ pressed }) => pressed && styles.swipePressed}
>
<View style={styles.archive}>
<Animated.View
style={[
styles.archive,
{
transform: [
{
scale: swipeAnimatedValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
extrapolate: "clamp",
}),
},
],
},
]}
>
<Ionicons
name="ios-archive-outline"
size={24}
color="white"
/>
</Animated.View>
</View>
</Pressable>
) : (
<Pressable
onPress={unArchiveHandler.bind(this, item)}
style={({ pressed }) => pressed && styles.swipePressed}
>
<View style={styles.unArchive}>
<Animated.View
style={[
styles.unArchive,
{
transform: [
{
scale: swipeAnimatedValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
extrapolate: "clamp",
}),
},
],
},
]}
>
<Ionicons
name="md-duplicate-outline"
size={24}
color="white"
/>
</Animated.View>
</View>
</Pressable>
)}
<Pressable
onPress={deleteHandler.bind(this, item)}
style={({ pressed }) => pressed && styles.pressed}
>
<View style={styles.trash}>
<Animated.View
style={[
styles.trash,
{
transform: [
{
scale: swipeAnimatedValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
extrapolate: "clamp",
}),
},
],
},
]}
>
<Ionicons name="trash-outline" size={24} color="white" />
</Animated.View>
</View>
</Pressable>
</View>
);
},
[rightSwipeActions]
);
const deleteHandler = useCallback(
(item) => {
try {
sessionsCtx.deleteSession(item.id); // delete from local context
const uid = auth.currentUser.uid;
const sessionRef = ref(
database,
"users/" + uid + "/sessions/" + item.id
);
remove(sessionRef); // delete from firebase
} catch (error) {
alert(error.message);
}
},
[deleteHandler]
);
const archiveHandler = (item) => {
try {
const id = item.id;
const updatedSession = {
...item, // copy current session
archived: true,
};
const uid = auth.currentUser.uid;
const sessionRef = ref(database, "users/" + uid + "/sessions/" + id);
update(sessionRef, updatedSession);
/* sessionsCtx.updateSession(id, updatedSession); */
//update inbox state
setInbox(
currentSessions.filter((session) => {
const updatedData = session.archived === false;
return updatedData;
})
);
//update archive state
setArchive(
currentSessions.filter((session) => {
const updatedData = session.archived === true;
return updatedData;
})
);
} catch (error) {
alert(error.message);
}
};
const unArchiveHandler = (item) => {
try {
const id = item.id;
const updatedSession = {
...item, // copy current session
archived: false,
};
const uid = auth.currentUser.uid;
const sessionRef = ref(database, "users/" + uid + "/sessions/" + id);
update(sessionRef, updatedSession);
/* sessionsCtx.updateSession(id, updatedSession); */
//update unarchived session list
setArchive((preState) => {
//remove the item from archived list
preState.filter((session) => session.id !== item.id);
return [...preState];
});
} catch (error) {
alert(error.message);
}
};
const selectSessionHandler = useCallback(
(selectedItem) => {
switch (selectedItem) {
case "Sessions":
setStream(inbox);
break;
case "Archive":
setStream(archive);
break;
}
},
[selectSessionHandler, inbox, archive]
);
const selectFilterHandler = (selectedItem) => {
//filter the session list
switch (selectedItem) {
case "ABC":
// Use the Array.sort() method to sort the list alphabetically in ascending order
const sortedList = stream.sort((a, b) => {
return a.title.localeCompare(b.title);
});
setStream((preState) => {
return [...sortedList];
});
break;
case "CBA":
// Use the Array.sort() method to sort the list alphabetically in descending order
const sortedList2 = stream.sort((a, b) => {
return b.title.localeCompare(a.title);
});
setStream((preState) => {
return [...sortedList2];
});
break;
case "Latest Date":
// Use the Array.sort() method to sort the list by date in descending order
const sortedList3 = stream.sort((a, b) => {
return b.date.localeCompare(a.date);
});
setStream((preState) => {
return [...sortedList3];
});
break;
case "Earliest Date":
// Use the Array.sort() method to sort the list by date in ascending order
const sortedList4 = stream.sort((a, b) => {
return a.date.localeCompare(b.date);
});
setStream((preState) => {
return [...sortedList4];
});
break;
}
};
const renderSessionItem = useCallback(({ item }) => {
return (
<Pressable
/* style={({ pressed }) => pressed && styles.pressed} */
onPress={onPressHandler.bind(null, item)}
key={item.id}
>
<SessionComponent
key={item.id}
title={item.title}
identifier={item.identifier}
date={item.date}
rightSwipeActions={rightSwipeActions.bind(null, item)}
smed={item.smed}
endTime={item.endTime}
/>
</Pressable>
);
}, []);
return (
<View style={styles.container}>
<View style={styles.menuRow}>
<SelectBtn
data={sortList}
onSelect={(item) => selectFilterHandler(item)}
/>
<SelectBtn
data={sessionList}
onSelect={(item) => selectSessionHandler(item)}
/>
</View>
<FlatList
data={stream}
renderItem={renderSessionItem}
keyExtractor={(item) => item.id}
extraData={stream}
/>
</View>
);
}
export default SessionStream;
What I already tried:
I tried ChatGPT the whole day yesterday ... ;-)
I tried updating the global state for sessions to trigger re-renders ...
I tried updating the local state as obj or via the spread operator to ...
I tried extraData prop at FlatList
I removed useCallback to make sure it doesnt somehow block ...
can you do this when you are updating your stream state
const oldStream = stream;
const newStream = newStream; // put the value that you have updated
const returnedTarget= Object.assign(stream, newStream);
setStream(returnedTarget);
The problem might be you are mutating the copy obj
ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
c) in your selectFilterHandler method you are updating filter and in the same method you are trying to use updated filter value. which is not possible as useState does not update value immediately.
b) in your archiveHandler i think you are not updating the setStream state. if you are trying to run
const selectSessionHandler = useCallback(
(selectedItem) => {
switch (selectedItem) {
case "Sessions":
setStream(inbox);
break;
case "Archive":
setStream(archive);
break;
}
},
[selectSessionHandler, inbox, archive]
);
this method whenever inbox/archive changes it will not work it will be work only when you call this method and any of the value in dependency array has changed. (you can use useEffect and pass and deps arr [inbox,archive] which will run every time and can update your state.

Apollo cache query fields policy offsetLimitPagination() doesnt work with subscriptions

I use apollo client for react native.
When I use offsetLimitPagination() for pagination my subscriptions doesn't update cache.
Subscriptions works correctly but doesn't update flatlist data.
When i remove offsetLimitPagination function it works. I can't use together subscriptions and offsetLimitPagination function on cache.
Is there any solution for that?`
Thanks.
Cache
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
chatDetail: offsetLimitPagination(),
}
}
},
});
ChatDetailPage
import React, { useState, useCallback } from 'react'
import { StyleSheet, Text, View, FlatList } from 'react-native'
import { ActivityIndicator } from 'react-native-paper';
import { useQuery } from '#apollo/client'
import { useSelector } from 'react-redux'
import { CHAT_DETAIL } from '../../../Graphql/Queries/Message'
import { MESSAGE_SUB } from '../../../Graphql/Subscriptions/Message'
import MainFlow from './Components/Flow/MainFlow'
const ChatDetailMain = () => {
const user = useSelector(state => state.auth.user)
const currentRoom = useSelector(state => state.room.currentRoom)
const [hasNext, setHasNext] = useState(true)
const limit = 15
const { error, loading, data, refetch, fetchMore, subscribeToMore } = useQuery(CHAT_DETAIL, {
variables: { userId: user._id, roomId: currentRoom._id, limit }, fetchPolicy: "cache-and-
network",
nextFetchPolicy: "cache-first" })
// render item
const renderItem = (
({item} ) => {
return <MainFlow item={item} />
}
)
if (error) {
console.warn('CHAT_DETAIL QUERY ERROR: ', error)
console.log(error.message);
return (
<View>
<Text>
An Error Occured: {error.message}
</Text>
</View>
)
}
if (loading || data == undefined || data == null) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator size={50} color="gray" />
</View>
)
}
// fetchMore
const fetchMoreData=()=>{
// console.log("fetchMore runnig hasnext limit, data.chatDetail.length >= limit ", hasNext, limit, data.chatDetail.length >= limit);
if(hasNext && data.chatDetail.length >= limit){
fetchMore({
variables:{
offset: data.chatDetail.length,
limit: data.chatDetail.length+limit
}
}).then((flowMoredata)=>{
if(flowMoredata.data.chatDetail.length==0 || flowMoredata.data.chatDetail.length === data.chatDetail.length){
setHasNext(false)
}
})
}
}
// subscription area
const subscribeQ = () => subscribeToMore({
document: MESSAGE_SUB,
variables: {
userId: user._id
},
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const { messageSub } = subscriptionData.data
let current = {}
let others = []
switch(messageSub.type){
case 'update':
prev.chatDetail.map(message => {
if (message._id != messageSub.message._id) others.push(message)
if (message._id == messageSub.message._id) current = messageSub.message
})
return { chatDetail: [ current, ...others ]}
case 'remove':
prev.chatDetail.map(message => {
if (message._id != messageSub.message._id) others.push(message)
if (message._id == messageSub.message._id) current = messageSub.message
})
return { chatDetail: [ ...others ]}
case 'create':
return { chatDetail: { ...prev, chatDetail: [ messageSub.message, ...prev.chatDetail] }}
default: return { ...prev }
}
}
})
if (subscribeToMore != undefined && subscribeToMore) {
subscribeQ()
}
return (
<View>
<FlatList
data={data.chatDetail}
renderItem={renderItem}
keyExtractor={(item, index) => String(index)}
onEndReached={fetchMoreData}
onEndReachedThreshold={0.2}
contentContainerStyle={{ paddingTop: 80 }}
inverted={true}
/>
</View>
)
}
export default ChatDetailMain
const styles = StyleSheet.create({})
It was about cache merge issue. If you want to cache data, you shoul give a key to apollo client "Cache according to the what, for each room has an id or roomName for keyArgs param it should uniqe value like that
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
chatDetail: {
keyArgs:['roomId'],
merge(incoming=[], existing=[]){
.
.
.
return offsetLimitPagination()
}}
}
}
},
});

How to load contact details into multi select drop down in react native?

I am creating a react native app to load phone book contacts to my app using this library. I loaded contact correctly in my app. Now I wanted to load these contact details in to multi select drop down. I used react-native-multiple-select to load contact using this library. But I am not be able load contact into this library.
The UI that I need to load contact details.
This is what I tried,
import React, {Component} from 'react';
import {
View,
Text,
TouchableOpacity,
FlatList,
ActivityIndicator,
Image,
TextInput,
PermissionsAndroid,
Platform,
Modal,
TouchableHighlight,
Alert,
} from 'react-native';
import ContactsLib from 'react-native-contacts';
import {styles} from '../src/HomeTabs/ContactStyles';
import PropTypes from 'prop-types';
import {Header} from 'react-native-elements';
import MultiSelect from 'react-native-multiple-select';
//Import MultiSelect library
export class Tab2 extends Component {
constructor(props) {
super(props);
this.state = {
contactList: [],
selectedContact: [],
text: '',
isLoading: true,
show: false,
modalVisible: false,
};
this.arrayholder = [];
}
async componentDidMount() {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
title: 'App Contact Permission',
message: 'This App needs access to your contacts ',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.getListOfContacts();
this.showconsole();
} else {
this.setState({isLoading: false});
this.getOtherContacts();
}
} catch (err) {
this.setState({isLoading: false});
}
} else {
ContactsLib.checkPermission((err, permission) => {
if (permission === 'denied') {
this.setState({isLoading: false});
this.getOtherContacts();
} else {
this.getListOfContacts();
}
});
}
}
// Mics Method
getOtherContacts = () => {
const {otherContactList} = this.props;
const arrFinal = [];
if (otherContactList.length > 0) {
otherContactList.map(listItem => {
arrFinal.push(listItem);
});
}
arrFinal.map((listItem, index) => {
listItem.isSelected = false;
listItem.id = index;
});
this.setState({contactList: arrFinal, isLoading: false});
this.arrayholder = arrFinal;
};
getListOfContacts = () => {
const {otherContactList} = this.props;
const arrFinal = [];
ContactsLib.getAll((err, contacts) => {
if (err) {
throw err;
}
contacts.map(listItem => {
arrFinal.push({
fullname: listItem.givenName + ' ' + listItem.familyName,
phoneNumber:
listItem.phoneNumbers.length > 0
? listItem.phoneNumbers[0].number
: '',
avatar: listItem.thumbnailPath,
});
});
if (otherContactList.length > 0) {
otherContactList.map(listItem => {
arrFinal.push(listItem);
});
}
arrFinal.map((listItem, index) => {
listItem.isSelected = false;
listItem.id = index;
});
this.setState({contactList: arrFinal, isLoading: false});
this.arrayholder = arrFinal;
});
};
getSelectedContacts = () => {
const {selectedContact} = this.state;
return selectedContact;
};
checkContact = item => {
const {onContactSelected, onContactRemove} = this.props;
let arrContact = this.state.contactList;
let arrSelected = this.state.selectedContact;
arrContact.map(listItem => {
if (listItem.id === item.id) {
listItem.isSelected = !item.isSelected;
}
});
if (item.isSelected) {
arrSelected.push(item);
if (onContactSelected) {
onContactSelected(item);
}
} else {
if (onContactRemove) {
onContactRemove(item);
}
arrSelected.splice(arrSelected.indexOf(item), 1);
}
this.setState({contactList: arrContact, selectedContact: arrSelected});
};
checkExist = item => {
const {onContactRemove} = this.props;
let arrContact = this.state.contactList;
let arrSelected = this.state.selectedContact;
arrContact.map(listItem => {
if (listItem.id === item.id) {
listItem.isSelected = false;
}
});
if (onContactRemove) {
onContactRemove(item);
}
arrSelected.splice(arrSelected.indexOf(item), 1);
this.setState({contactList: arrContact, selectedContact: arrSelected});
};
SearchFilterFunction = text => {
let newArr = [];
this.arrayholder.map(function(item) {
const itemData = item.fullname.toUpperCase();
const textData = text.toUpperCase();
if (itemData.indexOf(textData) > -1) {
newArr.push(item);
}
});
this.setState({
contactList: newArr,
text: text,
});
};
//Render Method
_renderItem = ({item}) => {
const {viewCheckMarkStyle} = this.props;
return (
<TouchableOpacity onPress={() => this.checkContact(item)}>
<View style={styles.viewContactList}>
<Image
source={
item.avatar !== ''
? {uri: item.avatar}
: require('../images/user.png')
}
style={styles.imgContactList}
/>
<View style={styles.nameContainer}>
<Text style={styles.txtContactList}>{item.fullname}</Text>
<Text style={styles.txtPhoneNumber}>{item.phoneNumber}</Text>
</View>
{item.isSelected && (
<Image
source={require('../images/check-mark.png')}
style={[styles.viewCheckMarkStyle, viewCheckMarkStyle]}
/>
)}
</View>
</TouchableOpacity>
);
};
state = {
//We will store selected item in this
selectedItems: [],
};
onSelectedItemsChange = selectedItems => {
this.setState({selectedItems});
//Set Selected Items
};
render() {
const {selectedItems} = this.state;
const {searchBgColor, searchPlaceholder, viewSepratorStyle} = this.props;
return (
<View style={styles.container}>
<MultiSelect
hideTags
items={this.contactList}
uniqueKey="id"
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={this.onSelectedItemsChange}
selectedItems={selectedItems}
selectText="Select Contacts"
searchInputPlaceholderText="Search Contacts..."
onChangeInput={text => console.log(text)}
tagRemoveIconColor="#ff0000"
tagBorderColor="#48d22b"
tagTextColor="#000"
selectedItemTextColor="#48d22b"
selectedItemIconColor="#48d22b"
itemTextColor="#000"
displayKey="name"
searchInputStyle={{color: '#48d22b'}}
submitButtonColor="#48d22b"
submitButtonText="Submit"
/>
<View>
{this.multiSelect &&
this.multiSelect.getSelectedItemsExt(selectedItems)}
</View>
{this.state.isLoading && (
<View style={styles.loading}>
<ActivityIndicator animating={true} size="large" color="gray" />
</View>
)}
</View>
);
}
}
Tab2.propTypes = {
otherContactList: PropTypes.array,
viewCloseStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
]),
viewCheckMarkStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
]),
sepratorStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
]),
viewSepratorStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.object,
]),
searchBgColor: PropTypes.string,
searchPlaceholder: PropTypes.string,
onContactSelected: PropTypes.func,
onContactRemove: PropTypes.func,
};
Tab2.defaultProps = {
otherContactList: [],
viewCloseStyle: {},
viewCheckMarkStyle: {},
sepratorStyle: {},
viewSepratorStyle: {},
searchBgColor: 'rgb(202,201,207)',
searchPlaceholder: 'Search...',
onContactSelected: () => {},
onContactRemove: () => {},
};
export default Tab2;
your multiselect should be given the contacts. Try stripping out anything nonessential from your example
...
render() {
...
return (
...
<MultiSelect
items={this.state.contactList}
...
/>
...
);
}

React Native image picker is showing image too slow after successfully uploading

after uploading image successfully the uploaded image is taking time to show ?
anyone knows anything about it?
here is my code
_onPressEdit = () => {
ImagePicker.showImagePicker(options, response => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
this._uploadImage(response.uri);
}
});
};
here is my full code
import React, {PureComponent} from 'react';
import {View, Text, Image, PermissionsAndroid, Platform} from 'react-native';
import {connect} from 'react-redux';
import ImagePicker from 'react-native-image-picker';
import styles from './styles';
import {Images, Styles, Language, Colors} from '#theme';
import {Wrapper, Input, ButtonView} from '#components';
import {TextInputField} from '#customComponents';
import {Navigator} from '#services';
import StarRating from 'react-native-star-rating';
import Header from '../Header';
import Footer from '../Footer';
import {uploadImage, editProfile} from '../../../actions/UserActions';
import {BASE_URL_PHOTO} from '../../../config/WebService';
import {selectUserData} from '../../../selectors/userSelector';
import {UserPresenter} from '../../../presenter';
import {Util} from '../../../utils';
const options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
};
class Profile extends PureComponent {
constructor(props) {
super(props);
const {firstName, lastName, email, mobile, image, id} = this.props.user;
this.state = {
id,
firstName,
lastName,
email,
mobile,
image,
errors: {},
};
}
onStarRatingPress(rating) {
this.setState({
starCount: rating,
});
}
checkAllPermissions = async () => {
try {
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.CAMERA,
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
]);
if (
(await PermissionsAndroid.check('android.permission.CAMERA')) &&
(await PermissionsAndroid.check('android.permission.CAMERA')) &&
(await PermissionsAndroid.check('android.permission.CAMERA'))
) {
this._onPressEdit();
return true;
} else {
console.log('all permissions denied');
return false;
}
} catch (err) {
console.warn(err);
}
};
_onPressEdit = () => {
ImagePicker.showImagePicker(options, response => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
this._uploadImage(response.uri);
}
});
};
_uploadImage = image => {
const {uploadImage} = this.props;
const {id} = this.props.user;
UserPresenter.sendUploadAvatarRequest(
uploadImage,
image,
id,
this._onSuccessImageUpload,
);
};
_onSuccessImageUpload = uri => {
this.setState({
image: uri,
});
};
_onChangeText = (key, value) => {
this.setState(
{
[key]: value,
},
() => console.log(this.state),
);
};
_validateForm = () => {
const {firstName, lastName, mobile} = this.state;
const errors = UserPresenter.getEditProfileErrors(
firstName,
lastName,
mobile,
);
this.setState({errors});
return Util.isEmpty(errors);
};
_onPressSave = () => {
const {firstName, lastName, mobile, image} = this.state;
const {id} = this.props.user;
const {editProfile} = this.props;
if (this._validateForm()) {
UserPresenter.sendEditProfileRequestStepOne(
editProfile,
id,
firstName,
lastName,
mobile,
image,
this._onSuccessSave,
);
}
};
_onSuccessSave = () => {
// Navigator.pop();
Navigator.goBack();
};
_onPressNext = () => {
if (this._validateForm()) {
Navigator.navigate('EditProfileServices', {data: this.state});
}
};
onPressFooterBtn = () => {
Navigator.navigate('EditProfileServices');
};
renderStarRating() {
const {rating} = this.props.user;
return (
<StarRating
starSize={24}
starStyle={styles.starStyle}
halfStarEnabled={true}
halfStarColor={Colors.textWhiteTwo}
emptyStarColor={Colors.textWhiteTwo}
disabled={true}
maxStars={5}
rating={rating}
selectedStar={rating => this.onStarRatingPress(rating)}
/>
);
}
renderEditFields() {
const {firstName, lastName, email, mobile, errors} = this.state;
return (
<View>
<TextInputField
title={Language.firstName}
placeholder={Language.Andrew}
value={firstName}
onChangeText={text => this._onChangeText('firstName', text)}
error={errors.firstName}
/>
<TextInputField
title={Language.lastName}
placeholder={Language.Crammer}
value={lastName}
onChangeText={text => this._onChangeText('lastName', text)}
error={errors.lastName}
/>
<TextInputField
title={Language.email}
keyboardType={'email-address'}
placeholder={Language.andrewCrammerEmail}
value={email}
onChangeText={text => this._onChangeText('email', text)}
error={errors.email}
editable={false}
/>
<TextInputField
title={Language.phone}
keyboardType={'phone-pad'}
placeholder={Language.EditProfilePhonePlaceholder}
value={mobile}
onChangeText={text => this._onChangeText('mobile', text)}
error={errors.mobileNumber}
/>
{/* <Input
label={Language.changePassword}
secureTextEntry={true}
placeholder={Language.EditProfileChangePassword}
/> */}
</View>
);
}
renderBody() {
const {rating} = this.props.user;
const {image} = this.state;
return (
<View style={Styles.paddingHorizontal}>
<View
style={[
Styles.flexDirectionRow,
Styles.alignItemsCenter,
styles.mb_30,
]}>
<View style={styles.editProfileImgWrap}>
<Image
style={styles.imgStyle}
source={{uri: `${BASE_URL_PHOTO}${image}`}}
/>
<ButtonView
isBackgroundRipple
onPress={
Platform.OS === 'android'
? this.checkAllPermissions
: this._onPressEdit
}
style={[Styles.positionAbsolute, styles.editWrap]}>
<Text style={styles.edit}>{Language.edit}</Text>
</ButtonView>
</View>
<View>
<Text style={styles.textStyle}>{Language.ProfilePicture}</Text>
</View>
</View>
<View style={styles.starStyleWrap}>
{this.renderStarRating()}
<Text style={styles.starRatingText}>{rating}</Text>
</View>
<View>{this.renderEditFields()}</View>
</View>
);
}
renderHeader() {
return <Header onPressSave={this._onPressSave} />;
}
renderFooter() {
return <Footer onPressNext={this._onPressNext} step={1} />;
}
//Render
render() {
return (
<Wrapper
header={this.renderHeader()}
footer={this.renderFooter()}
isFetching={this.props.isFetching}
isAbsolute
mainContainerStyle={Styles.paddingHorizontalNone}
isScrollView>
{this.renderBody()}
</Wrapper>
);
}
}
const mapStateToProps = state => {
return {
user: selectUserData(state.user),
isFetching: state.user.isFetching,
};
};
const actions = {uploadImage, editProfile};
export default connect(mapStateToProps, actions)(Profile);
issue solved
just compress your image size so it wont take time to appear
here is the code
const options = {
title: 'Select Picture',
storageOptions: {
skipBackup: true,
path: 'images',
},
maxWidth: 500,
maxHeight: 500,
quality: 0.5,
};
previous code was
const options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
};

State is not updating even by callvack in render

i am trying to fetch data from some source and storing it in some variable .
But I come with an error that state is not updating.
this.setState({imgLink: data.items[0].snippet.thumbnails.default.url},
() =>
{
console.log(this.state.imgLink);
});
I wanted to print the new value in render method but it shows me nothing.
import React,{Component} from 'react';
import {View,Text,TextInput,ScrollView,Image} from
'react-native';
import { Icon } from 'react-native-elements';
import YTSearch from 'youtube-api-search';
import styles from './StatsStyle';
const API_KEY = '' // hided for stackoverflow ;
var query = '';
export default class StatsScreen extends Component
{
constructor(props)
{
super(props);
this.state = {
term: '',
imgLink: '',
width: 0,
height: 0,
title: '',
totalViews: 0,
totalSubs: 0,
totalVideos: 0 ,
channelId : '' ,
url: '',
}
};
fetchData = data => {
console.log('this is fetchData',data.items[0].statistics.subscriberCount);
this.setState({imgLink: data.items[0].snippet.thumbnails.default.url},
() =>
{
console.log('llllll',this.state.imgLink);
});
console.log('llllll',this.state.imgLink);
this.setState({width: data.items[0].snippet.thumbnails.default.url.width});
this.setState({height: data.items[0].snippet.thumbnails.default.url.height});
this.setState({title: data.items[0].snippet.title});
this.setState({totalSubs: data.items[0].statistics.subscriberCount});
this.setState({totalViews: data.items[0].statistics.viewCount});
this.setState({totalVideos: data.items[0].statistics.videoCount});
}
updateSubscribers = response =>
{
this.setState({totalSubs:
response.items[0].statistics.subscriberCount});
}
onPressedButton = channelId =>
{
var url =
'https://www.googleapis.com/youtube/v3/channels?
key='+API_KEY+'&id=' + channelId +
'&part=snippet,contentDetails,statistics';
this.setState({url: url});
return fetch(url)
.then((response) =>
{
return response.json();
console.log("popo",response);
})
// fetchData(data);
.then((data) => {
this.fetchData(data);
console.log('lol',this.state.imgLink);
console.log('hello',this.state);
})
.catch((error) => {
console.log(error);
})
//now fetching the response from the yt api again
//and again
.setInterval(() =>
{
var url =
'https://www.googleapis.com/youtube/v3/channels?
key='+API_KEY+'o&id=' + channelId +
'&part=statistics';
return fetch(url)
.then((response) =>
{
return response.json()
})
.then((data) => {
this.updateSubscribers(data)
},0)
.catch((error) => {
console.log(error);
});
});
}
render()
{
let{imgLink,totalSubs,totalViews,totalVideos,width,
height,title,channelId,videos,loading,term} =
this.state;
return(
<View style = {styles.container}>
<ScrollView>
<View style = {styles.results}>
<Image style = {
{
width:width,height:height,
alignItems:'center',borderRadius:50
,marginLeft:'auto',marginRight: 'auto',marginTop:
30
}
}
source = {{uri: imgLink}}/>
<Text style = {styles.title}>{title}</Text>
<Text style = {{fontSize: 40,fontWeight:
'bold'}}>Subscribers</Text>
<Text style = {styles.subs}>{totalSubs}</Text>
<Text style = {{fontSize: 40,fontWeight:
'bold'}}>TotalViews</Text>
<Text style = {styles.views}>{totalViews}</Text>
<Text style = {{fontSize: 40,fontWeight:
'bold'}}>TotalVideos</Text>
<Text style = {styles.videos}>{totalVideos}</Text>
</View>
</ScrollView>
</View>
);
}
}