RefrenceError: Can't find variable in react native - reactjs

I tried to access all the files in a custom folder I created on my RNCamera roll app to create a gallery with it. In my code I believe i specified the variable "videos", but still am getting a reference error: "can't find variable videos", what do i do to solve it, how will i be able to get rid of the error.... here is my code...
I added constructor in the this.state but still get the same error
constructor() {
super();
this.state = {
modalVisible: false,
videos: [],
index: null
}
}
getPhotos = () => {
CameraRoll.getPhotos({
first: 20,
groupTypes: 'Album',
groupName: 'Custom VideoFolder',
assetType: 'Videos'
})
.then(r => this.setState({ videos: r.edges}))
.then((statResult) => {
let videos = []
var allowedExtensions = /(\.avi|\.mp4|\.mov|\.wmv|\.avi)$/i;
statResult.forEach(item => {
if (item.isFile() && !allowedExtensions.exec(item.originalFilepath)) {
videos.push(item)
}
});
console.log(videos)
})
}
toggleModal = () => {
this.setState({ modalVisible: !this.state.modalVisible})
}
share = () => {
const vocvideo = this.state.videos[this.state.index].node.video.uri
RNFetchBlob.fs.readFile(vocvideo, 'uri')
.then((data) => {
let shareOptions = {
title: "React Native Share Example",
message: "Check out this video!",
url: `data:video/mp4;uri,${data}`,
subject: "Check out this video!"
};
Share.open(shareOptions)
.then((res) => console.log('res:', res))
.catch(err => console.log('err', err))
})
}
render() {
console.log('state :', this.state)
return (
<View style={styles.container}>
<Button
title='View videos'
onPress={() => { this.toggleModal(); this.getPhotos() }}
/>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => console.log('closed')}
>
<View style={styles.modalContainer}>
<Button
title='Close'
onPress={this.toggleModal}
/>
<ScrollView
contentContainerStyle={styles.scrollView}>
{
this.state.videos.map((p, i) => {
const isSelected = i === this.state.index;
const divide = isSelected && this.share === true ? 1 : 3;
return (
<Video
style={{opacity: i === this.state.index ? 0.5 : 1, width: width/divide, height: width/divide}}
key={i}
underlayColor='transparent'
onPress={() => this.setIndex(i)}
source={{uri: video}}
/>
)
})
}
</ScrollView>

Related

convert class components to functional components in react native?

I'm new to react native and I'm trying to upload multiple images using expo-image-picker-multiple but I'm having an error with the code so I'm trying to convert the class component to functional components so I can easily deal with it since I'm more familiar with functional components.
export default class ImageBrowse extends Component {
_getHeaderLoader = () => (
<ActivityIndicator size='small' color={'#0580FF'} />
);
imagesCallback = (callback) => {
const { navigation } = this.props;
this.props.navigation.setOptions({
headerRight: () => this._getHeaderLoader()
});
callback.then(async (photos) => {
const cPhotos = [];
for (let photo of photos) {
const pPhoto = await this._processImageAsync(photo.uri);
cPhotos.push({
uri: pPhoto.uri,
name: photo.filename,
type: 'image/jpg'
})
}
navigation.navigate('Main', { photos: cPhotos });
})
.catch((e) => console.log(e));
};
async _processImageAsync(uri) {
const file = await ImageManipulator.manipulateAsync(
uri,
[{ resize: { width: 1000 } }],
{ compress: 0.8, format: ImageManipulator.SaveFormat.JPEG }
);
return file;
};
_renderDoneButton = (count, onSubmit) => {
if (!count) return null;
return <TouchableOpacity title={'Done'} onPress={onSubmit}>
<Text onPress={onSubmit}>Done</Text>
</TouchableOpacity>
}
updateHandler = (count, onSubmit) => {
this.props.navigation.setOptions({
title: `Selected ${count} files`,
headerRight: () => this._renderDoneButton(count, onSubmit)
});
};
renderSelectedComponent = (number) => (
<View style={styles.countBadge}>
<Text style={styles.countBadgeText}>{number}</Text>
</View>
);
render() {
const emptyStayComponent = <Text style={styles.emptyStay}>Empty =(</Text>;
return (
<View style={[styles.flex, styles.container]}>
<ImageBrowser
max={4}
onChange={this.updateHandler}
callback={this.imagesCallback}
renderSelectedComponent={this.renderSelectedComponent}
emptyStayComponent={emptyStayComponent}
/>
</View>
);
}
}
Also this is related to the above code:
export default class MainScreen extends Component {
constructor(props) {
super(props)
this.state = {
photos: []
}
}
componentDidUpdate() {
const { params } = this.props.route;
if (params) {
const { photos } = params;
if (photos) this.setState({ photos });
delete params.photos;
}
}
renderImage(item, i) {
return (
<Image
style={{ height: 100, width: 100 }}
source={{ uri: item.uri }}
key={i}
/>
)
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={{ flex: 1 }}>
<Button
title="Open image browser"
onPress={() => { navigate('ImageBrowser'); }}
/>
<ScrollView>
{this.state.photos.map((item, i) => this.renderImage(item, i))}
</ScrollView>
</View>
);
}
}
The error is when I browse the gallery to select images nothing is showing:
And this warning showing to me:
Also this is what i came up with when I tried to convert class to functional components:
const PropertiesInfo = ({ navigation }) => {
const [attachments, setAttachments] = useState([]);
const componentDidUpdate=()=> {
const { params } = attachments.route;
if (params) {
const { attachments } = params
if (attachments) setAttachments({ attachments })
delete params.attachments
}
};
const renderImage=(item, i) =>{
return (
<Image
style={{ height: 100, width: 100 }}
source={{ uri: item.uri }}
key={i}
/>
)
};
return (
<View style={{ flex: 1 }}>
<Button
title="Open image browser"
onPress={() => { navigate('ImageBrowser'); }}
/>
<ScrollView>
{attachments.map((item, i) => renderImage(item, i))}
</ScrollView>
</View>
);
};
export default PropertiesInfo;
And this also:
const ImageBrowse=({ navigation })=> {
_getHeaderLoader = () => (
<ActivityIndicator size='small' color={'#0580FF'} />
);
imagesCallback = (callback) => {
navigation.setOptions({
headerRight: () => _getHeaderLoader()
});
callback.then(async (attachments) => {
const cPhotos = [];
for (let photo of attachments) {
const pPhoto = await _processImageAsync(photo.uri);
cPhotos.push({
uri: pPhoto.uri,
name: photo.filename,
type: 'image/jpg'
})
}
navigation.navigate('Main', { attachments: cPhotos });
})
.catch((e) => console.log(e));
};
const _processImageAsync = async (uri) => {
const file = await ImageManipulator.manipulateAsync(
uri,
[{ resize: { width: 1000 } }],
{ compress: 0.8, format: ImageManipulator.SaveFormat.JPEG }
);
return file;
};
_renderDoneButton = (count, onSubmit) => {
if (!count) return null;
return <TouchableOpacity title={'Done'} onPress={onSubmit}>
<Text onPress={onSubmit}>Done</Text>
</TouchableOpacity>
}
updateHandler = (count, onSubmit) => {
navigation.setOptions({
title: `Selected ${count} files`,
headerRight: () => _renderDoneButton(count, onSubmit)
});
};
renderSelectedComponent = (number) => (
<View style={styles.countBadge}>
<Text style={styles.countBadgeText}>{number}</Text>
</View>
);
const emptyStayComponent = <Text style={styles.emptyStay}>Empty =(</Text>;
return (
<View style={[styles.flex, styles.container]}>
<ImageBrowser
max={4}
onChange={updateHandler}
callback={imagesCallback}
renderSelectedComponent={renderSelectedComponent}
emptyStayComponent={emptyStayComponent}
/>
</View>
);
};
export default ImageBrowse;

React native updating every 6th state automatically

Whenever I press the heart button it updates the state and calls renderHeart method in TutorsCard.js but it also updates every 6th card's state and so on when I scroll down to fetch more profiles so they appear to be liked as well. It might be an issue of shouldComponentUpdate in TutorsCard.js I change shouldComponentUpdate multiple times but it didn't work.
Feed.js
class Feed extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
profiles: new DataProvider((r1, r2) => {
return r1 !== r2;
}),
loading: false,
liked: false,
color: 'red',
refreshing: false,
limit: 10
};
this.layoutProvider = new LayoutProvider((i) => 0, (type, dim) => {
dim.width = width;
dim.height = 250;
})
}
onRefresh = () => {
this.getProfiles();
}
shouldComponentUpdate(nextProps, nextState) {
if (JSON.stringify(this.props) === JSON.stringify(nextProps) &&
this.state === nextState) {
console.log("should cmp update feed false")
return false
}
if (JSON.stringify(this.props) !== JSON.stringify(nextProps) ||
this.state !== nextState) {
console.log("should cmp update feed true")
return true
}
}
onEndReach = async () => {
this.setState({ limit: this.state.limit + 10 }, this.getProfiles)
}
rowRenderer = (type, data) => {
return (
<TutorCard
item={data}
navigation={this.props.navigation}
liked={
this.props.auth.likedProfiles.some((user) => user.id === data._id)
? true
: false
}
/>
);
}
TutorCard.js
class TutorCard extends Component {
state = {
liked: false,
};
shouldComponentUpdate(nextProps, nextState){
if(JSON.stringify(this.props.item._id) === JSON.stringify(nextProps.item._id) &&
this.state.liked === nextState.liked){
console.log("should cmp update tutors card false")
return false
}
if(JSON.stringify(this.props.item._id) !== JSON.stringify(nextProps.item._id) ||
this.state.liked !== nextState.liked){
console.log("should cmp update tutors card true")
return true
}
}
async likedCard() {
//server request
this.setState({ liked: false });
const res = await axios.post(IP_ADDRESS + '/api/removeLikedProfile',
{ id: this.props.item._id });
this.props.fetchCurrentUser()
}
async dislikeCard() {
//server request
this.setState({ liked: true });
const res = await axios.post(IP_ADDRESS + '/api/addLikedProfile',
{ id: this.props.item._id });
this.props.fetchCurrentUser()
}
capitalize = str => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
renderHeart = () => {
if (!this.props.liked && !this.state.liked) {
return (
<TouchableOpacity onPress={() => this.dislikeCard()}>
<AntDesign name="hearto" size={normalize(23)} color="#26a03a" />
</TouchableOpacity>
);
}
if(this.props.liked || this.state.liked){
return (
<TouchableOpacity onPress={() => this.likedCard()}>
<AntDesign name="heart" size={normalize(23)} color="red" />
</TouchableOpacity>
);
}
}
render() {
return (
<View>
<Button style={{
flexDirection: 'row', flex: 1,
justifyContent: 'flex-end'
}}
transparent>{this.renderHeart()}</Button>
</View>
);
}
}

React state is not updated immediately after deleting data

I have a problem to update the view in React Native after deleting a POST.
I think it could be a problem with the "state" but don't know how to fix it.
This is my list of Posts.
When I press on an item, it ask us to confirm the action.
When we confirm the action of delete, POST is deleted from Firebase but the view is not updated (Still 2 items in the list but only one in database. if I refresh and re-enter to the component, the list is updated)
This is my code :
class GetPosts extends React.Component {
static navigationOptions = ({navigation}) => {
const {params} = navigation.state;
};
constructor(props) {
super(props);
this.state = {
data: {},
data2: [],
posts: {},
newArray: [],
postsCount: 0,
};
}
componentDidMount() {
var f_id = this.props.identifier;
firebase
.database()
.ref('/posts/')
.orderByKey()
.on('value', snapshot => {
snapshot.forEach(el => {
if (el.val().film_id == f_id) {
this.state.data = [
{
email: el.val().email,
puid: el.val().puid,
username: el.val().username,
time: el.val().time,
text: el.val().text,
},
];
this.setState({
data2: this.state.data2.concat(this.state.data),
});
}
});
this.state.data2.forEach(obj => {
if (!this.state.newArray.some(o => o.puid === obj.puid)) {
this.state.newArray.push({...obj});
}
});
this.setState({
posts: this.state.newArray,
postsCount: _.size(this.state.newArray),
});
console.log('valeur finale POSTS=' + this.state.posts);
});
}
renderPosts() {
const postArray = [];
_.forEach(this.state.posts, (value, index) => {
const time = value.time;
const timeString = moment(time).fromNow();
postArray.push(
<TouchableOpacity
onLongPress={this._handleDelete.bind(this, value.puid)}
key={index}>
<PostDesign
posterName={value.username}
postTime={timeString}
postContent={value.text}
/>
</TouchableOpacity>,
);
//console.log(postArray);
});
_.reverse(postArray);
return postArray;
}
_handleDelete(puid) {
const email = firebase.auth().currentUser.email;
let user_email = firebase.database().ref('/posts');
user_email.once('value').then(snapshot => {
snapshot.forEach(el => {
console.log('Userdb :' + el.val().email);
if (email === el.val().email) {
Alert.alert(
'Supprimer le message',
'Are you sure to delete the post?',
[
{text: 'Oui', onPress: () => this._deleteConfirmed(puid)},
{text: 'Non'},
],
);
//console.log('Userdb :' + el.val().email);
} else {
//
console.log('Usercur :' + email);
}
});
});
}
_deleteConfirmed(puid) {
const uid = firebase.auth().currentUser.uid;
firebase
.database()
.ref('/posts/' + uid + puid)
.remove();
this.setState({
posts: this.state.newArray.filter(user => user.puid !== puid),
});
}
render() {
return (
<View style={styles.container}>
<View style={styles.profileInfoContainer}>
<View style={styles.profileNameContainer}>
<Text style={styles.profileName}>{this.props.email}</Text>
</View>
<View style={styles.profileCountsContainer}>
<Text style={styles.profileCounts}>{this.state.postsCount}</Text>
<Text style={styles.countsName}>POSTS</Text>
</View>
</View>
<ScrollView styles={styles.postContainer}>
{this.renderPosts()}
</ScrollView>
</View>
);
}
}
Thank you in advance !!
Several places in your code you are accessing this.state inside of setState, which can cause problems like this. You should be using a function with prevProps whenever you are accessing state within setState.
For example, within _deleteConfirmed:
this.setState({
posts: this.state.newArray.filter(user => user.puid !== puid),
});
should be changed to:
this.setSate(prevState => ({
posts: prevState.newArray.filter(user => user.puid !== puid),
});

React-Native setState not updating during fetch()

I have 3 records in my table, I can see the app fetches record to my remote because I console.log the response. My problem is that it will not display the item.
I know I defined correctly the column in FlatList because If I will set the per_page=1 which means pull 1 record every request. It will display but 2 records only will display the last record will not, if I set to per_page=30 nothing displays. is there a problem in my setState() during the response ?.I heard that setSate is not mutable..how can I apply the updater function of setsate in my code.?...I am still fresh on react native I hope someone will help me here.
I tried to do this but no luck!..also is this will matter that I use react-redux in my other page then in this screen I did not use only handling of state. ?...please help me react-native experts.
this.setState({
page: this.getParameterByName('page', res.next_page_url),
data: this.state.page === 1 ? res.data : [...this.state.data, ...res.data],
error: res.error || null,
loading: false,
refreshing: false,
last_page: res.last_page
},()=>{
return this.state;
});
Here is my complete code
import React, { Component } from 'react';
import {ScrollView, Text, View, Button, FlatList, ActivityIndicator} from 'react-native';
import { List, ListItem, Icon } from "react-native-elements";
import {connect} from "react-redux";
import numeral from "numeral";
import Moment from 'react-moment';
import moment from 'moment';
class Screen1 extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
per_page: 30,
order_by:'id',
sort_by:'asc',
error: null,
refreshing: false,
param:'',
last_page:''
};
}
componentDidMount() {
this.makeRemoteRequest();
}
makeRemoteRequest = () => {
const {page, per_page,order_by,sort_by } = this.state;
const url = `http://myapp.com/api/mobile/credit?page=${page}&api_token=${this.props.token}&per_page=${per_page}&order_by=${order_by}&sort_by=${sort_by}`;
console.log("the url",url);
this.setState({ loading: true });
setTimeout(()=>{
fetch(url)
.then(res => res.json())
.then(res => {
console.log("the page is =",this.getParameterByName('page',res.next_page_url));
this.setState({
page:this.getParameterByName('page',res.next_page_url),
data: this.state.page === 1 ? res.data : [...this.state.data,...res.data],
error: res.error || null,
loading: false,
refreshing: false,
last_page: res.last_page
});
})
.catch(error => {
this.setState({ error, loading: false });
});
},1500);
};
handleRefresh = () => {
if( this.state.page) {
if (this.state.page <= this.state.last_page) {
this.setState(
{
refreshing: true,
page: this.state.page
},
() => {
this.makeRemoteRequest();
}
);
}
}
};
getParameterByName = (name,url) =>{
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return parseInt(decodeURIComponent(results[2].replace(/\+/g, " ")), 10);
};
handleLoadMore = () => {
if( this.state.page){
if( this.state.page <= this.state.last_page ){
this.setState(
{
page: this.state.page
},
() => {
this.makeRemoteRequest();
}
);
}else{
console.log("cannot handle more",this.state.page)
}
}else{
console.log("page is null");
}
};
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
marginLeft: "14%"
}}
/>
);
};
renderHeader = () => {
return (
<View >
<Text h1
style={{
color: 'blue',
fontWeight: 'bold',
textAlign: 'center',
fontSize: 30,
backgroundColor: "#CED0CE",
}}
>{ numeral(this.props.thetotalcredit).format("#,##0.00") }</Text>
</View>
);
};
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: "#CED0CE"
}}
>
<ActivityIndicator animating size="large" />
</View>
);
};
render() {
return (
<FlatList
data={this.state.data}
keyExtractor = {(item, index) => index.toString()}
renderItem={({ item }) => (
<ListItem
title= { numeral(item.amountcredit).format("#,##0.00") }
subtitle= { moment(item.creditdate).format("MMM DD, YYYY") }
containerStyle={{ borderBottomWidth: 0 }}
/>
)}
extraData={this.state.data}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={0.5}
stickyHeaderIndices={[0]}
/>
);
}
}
const mapStateToProps = (state) => {
return {
username: state.auth.username,
token:state.auth.token,
thetotalcredit:state.auth.total_credit
};
};
export default connect(mapStateToProps)(Screen1);

React native delete multiple items from state array

I have a directory which stores images taken using the camera. For saving images I am using RNFS. I am using react-native-photo-browser.
The gallery itself doesn't have any options to delete the items from the gallery. So I am working to achieve it
export default class GridGallery extends React.Component{
static navigationOptions = {
title: 'Image Gallery',
};
constructor(props) {
super(props)
this.state = {
filesList : [],
mediaSelected: [],
base64URI: null,
galleryList: []
}
}
componentDidMount(){
FileList.list((files) => {
if(files != null) {
this.fileUrl = files[0].path;
files = files.sort((a, b) => {
if (a.ctime < b.ctime)
return 1;
if (a.ctime > b.ctime)
return -1;
return 0;
});
this.setState({
filesList: files
});
}
console.warn(this.state.filesList);
this.getFiles();
});
}
getFiles(){
//console.warn(this.state.filesList);
const ArrFiles = this.state.filesList.map((file) =>
({ caption : file.name, photo : file.path })
);
//console.warn(ArrFiles);
this.setState({ galleryList : ArrFiles });
}
onActionButton = (media, index) => {
if (Platform.OS === 'ios') {
ActionSheetIOS.showShareActionSheetWithOptions(
{
url: media.photo,
message: media.caption,
},
() => {},
() => {},
);
} else {
alert(`handle sharing on android for ${media.photo}, index: ${index}`);
}
};
handleSelection = async (media, index, isSelected) => {
if (isSelected == true) {
this.state.mediaSelected.push(media.photo);
} else {
this.state.mediaSelected.splice(this.state.mediaSelected.indexOf(media.photo), 1);
}
console.warn(this.state.mediaSelected);
}
deleteImageFile = () => {
const dirPicutures = RNFS.DocumentDirectoryPath;
//delete mulitple files
console.warn(this.state.mediaSelected);
this.state.mediaSelected.map((file) =>
// filepath = `${dirPicutures}/${file}`
RNFS.exists(`${file}`)
.then( (result) => {
console.warn("file exists: ", result);
if(result){
return RNFS.unlink(`${file}`)
.then(() => {
console.warn('FILE DELETED');
let tempgalleryList = this.state.galleryList.filter(item => item.photo !== file);
this.setState({ galleryList : tempgalleryList })
})
// `unlink` will throw an error, if the item to unlink does not exist
.catch((err) => {
console.warn(err.message);
});
}
})
.catch((err) => {
console.warn(err.message);
})
)
}
renderDelete(){
const { galleryList } = this.state;
if(galleryList.length>0){
return(
<View style={styles.topRightContainer}>
<TouchableOpacity style={{alignItems: 'center',right: 10}} onPress={this.deleteImageFile}>
<Image
style={{width: 24, height: 24}}
source={require('../assets/images/ic_delete.png')}
/>
</TouchableOpacity>
</View>
)
}
}
goBack() {
const { navigation } = this.props;
navigation.pop;
}
render() {
const { galleryList } = this.state;
return (
<View style={styles.container}>
<View style={{flex: 1}}>
<PhotoBrowser
mediaList={galleryList}
enableGrid={true}
displayNavArrows={true}
displaySelectionButtons={true}
displayActionButton={true}
onActionButton={this.onActionButton}
displayTopBar = {true}
onSelectionChanged={this.handleSelection}
startOnGrid={true}
initialIndex={0}
/>
</View>
{this.renderDelete()}
</View>
)
}
}
An example list of images:
[
{
photo:'4072710001_f36316ddc7_b.jpg',
caption: 'Grotto of the Madonna',
},
{
photo: /media/broadchurch_thumbnail.png,
caption: 'Broadchurch Scene',
},
{
photo:
'4052876281_6e068ac860_b.jpg',
caption: 'Beautiful Eyes',
},
]
My aim is whenever the item from state galleryList is removed I need to refresh the component, so the deleted image will be removed from the gallery. So When I try to use filter the galleryList it deleting other images instead of other images:
let tempgalleryList = this.state.galleryList.filter(item => item.photo !== file);
this.setState({ galleryList : tempgalleryList })
MCVE -> This is a minified version of my code, you can see the images are deleting randomly
Problem
let tempgalleryList = this.state.galleryList.filter(item => item.photo !== file);
this.setState({ galleryList : tempgalleryList })
Since setState is async, this.state.galleryList will not be updated in each iteration of your map function, so the final updated state will only have one item filtered out instead of all selected items.
Solution
You can use the callback version of setState which uses the updated state instead:
this.setState(prevState => ({
galleryList : prevState.galleryList.filter(item => item.photo !== file),
}));
Alternative solution
Instead of calling setState in every iteration, you can call it outside of your map function instead (though setState updates will be batched anyway so no significant performance improvement):
this.setState(prevState => ({
galleryList : prevState.galleryList.filter(item => !prevState.mediaSelected.includes(item.photo)),
}));
Other problems with your code
this.state.mediaSelected.push(media.photo);
} else {
this.state.mediaSelected.splice(this.state.mediaSelected.indexOf(media.photo), 1);
You are directly mutating your state here. Do this instead:
this.setState(prevState => ({
mediaSelected: prevState.mediaSelected.concat(media.photo)
}));
this.setState(prevState => ({
mediaSelected: prevState.mediaSelected.filter(e => e != media.photo)
}));

Resources