react native undefined is not an object, but I defined it - reactjs

Hi so I want to pass function to a functional component to execute. But i Get error undefined is not an object (evaluating '_this2.deleteChat')
Where I made mistake?
I often get this problem when using class components.
CLASS COMPONENT:
constructor(props) {
super(props);
this.state = { chats: [], usersData: [], userIDs: [], deletedChat: false };
this.getChats = this.getChats.bind(this);
this.deleteChat = this.deleteChat.bind(this);//DEFINED
}
deleteChat = chatID => {
const myId = firebase.auth().currentUser.uid;
let deleteData = firebase
.database()
.ref('/chats/' + chatID + '/members/')
.remove(myId);
this.setState({ ...this.state, deleteChat: !this.state.deletedChat });
};
...
return(
<TouchableHighlight
style={{ width: 65, height: 50 }}
title={data}
onPress={() =>
TwoButtonAlert(
'Do you realy wish to leave conversation?',
this.deleteChat(id),
)
}
>
...
My functional component
import React, { useState } from 'react';
import { Alert } from 'react-native';
const createTwoButtonAlert = (title, deleteChat) =>
Alert.alert(
title,
'My Alert Msg',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{ text: 'OK', onPress: () => deleteChat },
],
{ cancelable: false },
);
export default createTwoButtonAlert;
I have similar method but it runs in componentDidMount() and it works.
EXAMPLE:
componentDidMount() {
var _userId = firebase.auth().currentUser.uid;
this.getChats(_userId);
}
getChats = _userId => {
let data;
let usersData = [];
var readedData = firebase
.database()
.ref('chats')
.orderByChild('members/' + _userId)
.equalTo(true);
readedData.once('value', snapshot => {
data = snapshot.val();
// const temp = { ...data };
const filtered = Object.entries(data).map(([key, value]) =>
Object.keys(value)
.filter(value => value !== _userId)
.filter(value => value !== 'members')
.filter(value => value !== 'messages'),
);
this.setState({ chats: data, usersData: usersData, userIDs: filtered });
return true;
});
};

Two issues
You invoke deleteChat immediately when you pass it as this.deleteChat(id), which returns undefined since it is a VOID return
Attach it incorrectly in createTwoButtonAlert, i.e. () => deleteChat is improper syntax
Solution, convert to curried function to enclose the id in callback scope
deleteChat = chatID => () => {...
This will invoke the function immediately still, but this returns a function to be used as the callback.
Use the correct syntax to assign callback
onPress: () => deleteChat() // proxied callback
or
onPress: deleteChat // directly set the callback

Related

Updating Graph on Interval on React

I am getting data from my database to display it on the graph. Currently, I will have to refresh the page for the graph to update. I would like to refresh the graph in x interval as my data will be inserted at x interval. Am using ant design for the graph plotting. I am using a 'home' to display my graph and another class for my data fetching.
Home.js
export class Home extends Component {
static displayName = Home.name;
render () {
return (
<div>
<h1>Dashboard</h1>
<h2>
<div className="site-card-wrapper">
Graph1
<Graph />}
</div>
</h2>
</div>
);
}
}
Temp.js
const TempGraph = () => {
const [data, setData] = useState([]);
useEffect(() => {
asyncFetch();
}, []);
const asyncFetch = () => {
fetch('link')
.then((response) => response.json())
.then((json) => setDatajson))
.catch((error) => {
console.log('fetch data failed', error);
});
};
const config = {
data,
xField: 'time',
yField: 'value',
seriesField:'location',
xAxis: {
title: {
text: 'Hours',
}
},
yAxis:{
title:{
text: 'Temperature in °',
}
},
meta: {
time: {
alias: 'hours',
},
value: {
alias: 'temperature',
max: 50,
},
},
};
return <Line {...config} />;
}
export default TempGraph;
You could just add a setInterval in your useEffect to grab the data and update them again. Don't forgot to clear the interval on return:
useEffect(() => {
const interval = setInterval(() => asyncFetch(), 5000)
return () => clearInterval(interval)
}, []}
This example triggers every 5000ms, change the value according to your needs.

Reactjs passing data from child to parent

There is no problem in adding the because I successfully added data to my database but the problem is need to refresh the page before getting the updated data. this is the code ive done so far, this is the current error, did i miss something in my code? please help
note:
The child component will add data and the parent component will
display the latest data that the child component inserted
parent
const OvertimeType = () => {
const [reRender, setRerender] = useState(false);
....
const fetchData = async () => {
const response = await getDepartmentData('All', 100, 0);
response.data.map(function(u){
.....
})
}
useEffect(() => {
fetchData();
}, [reRender]);
const HandleAdd = (val) =>{
setRerender(val);
}
return (
<CustomToolbar sendToParent={HandleAdd()}/>
)
...
}
//
child
class CustomToolbar extends React.Component {
state = false;
HandleAdd = () => {
Swal.fire({
title: 'Add Over Time',
text: "Input overtime name below.",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Save',
html: generateInputForms({
strname: '',
intsequence: ''
}),
preConfirm: () => {
let strname = document.getElementById('strname').value;
let intsequence = document.getElementById('intsequence').value;
if (!strname) {
Swal.showValidationMessage('This field is required.')
}
if (!intsequence) {
Swal.showValidationMessage('This field is required.')
}
return {
strname: document.getElementById('strname').value,
intsequence: document.getElementById('intsequence').value
}
}
}).then((result) => {
if (result.isConfirmed) {
let request = {
strname:document.getElementById('strname').value,
intsequence:document.getElementById('intsequence').value
}
addDepartment(request).then(res =>{
if (res.status == 200){
Swal.fire({
icon: 'success',
title: 'Over Time',
text: 'New Data has been added successfully.',
}).then(res => {
this.sendToParent(res);
})
}else{
Swal.fire({
icon: 'error',
title: 'Oops',
text: 'Something went wrong.',
})
}
})
}
})
}
render() {
const { classes } = this.props;
return (
<React.Fragment>
<Tooltip title={"Add"}>
<Button
variant="contained"
onClick={this.HandleAdd}
className={classes.button}
startIcon={<AddIcon className={classes.addIcon} style={{color: '#fff',}} />}
>
Add
</Button>
</Tooltip>
</React.Fragment>
);
}
}
The problem is probably the way you pass the function
<CustomToolbar sendToParent={HandleAdd()}/>
A callback function should be sent like this without the parenthesis:
<CustomToolbar sendToParent={HandleAdd}/>
I see two issues here. First, as a few others have noted you'll want to pass the function, not invoke it.
<CustomToolbar sendToParent={HandleAdd}/>
Second, in this implementation sendToParent is defined on props, rather than a function in the class. To access it, you'll need to invoke it on this.props.
this.props.sendToParent(res);

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),
});

Using a function in Material-Table render property

I need to use a custom function in Material-Table column render property.
The function gets called, I get printed on the console the expected results, however, the result would simply not render in the table.
Here is the code:
import React from 'react';
import HraReferenceDataContext from '../context/hraReferenceData/hraReferenceDataContext';
import MaterialTable from 'material-table';
const EmployeeDetailsCompanyDocuments = ({ companyDocumentsData }) => {
const hraReferenceDataContext = React.useContext(HraReferenceDataContext);
const { companyDocumentTypes } = hraReferenceDataContext;
const getDocumentTypeForRow = id => {
companyDocumentTypes.forEach(type => {
if (type.id === id) {
console.log(type.name)
return type.name;
}
});
};
const columnInfo = [
{
field: 'typeId',
title: 'Type',
render: rowData =>{ getDocumentTypeForRow(rowData.typeId)}, //here is the problem
},
{ field: 'created', title: 'Created On' },
];
return (
<MaterialTable
columns={columnInfo}
data={companyDocumentsData}
title="Company Documents List"
/>
);
};
Returning inside forEach doesn't work.
change this function
const getDocumentTypeForRow = id => {
companyDocumentTypes.forEach(type => {
if (type.id === id) {
console.log(type.name)
return type.name;
}
});
};
to
const getDocumentTypeForRow = id => {
return companyDocumentTypes.find(type => type.id === id).name;
};
update
change
render: rowData =>{ getDocumentTypeForRow(rowData.typeId)},
to
render: rowData => getDocumentTypeForRow(rowData.typeId),
because you should return the value that is returned from getDocumentTypeForRow.

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