Invalid hook call. Hooks can only be called inside of the body of a function component. in react native signature canvas - react-native

I am new to react native. I have react native signature canvas code which is in functional component but now I write that code in my class component code. then I am getting error like this = Invalid hook call. Hooks can only be called inside of the body of a function component. so whats the issue please help.
here is code
export default class Kyc extends Component {
constructor(props) {
super(props);
this.state = {
singleFileSIGN:''
};
}
ref = useRef();
handleSignature = (signature) => {
const path = FileSystem.cacheDirectory + 'sign.png';
FileSystem.writeAsStringAsync(path, signature.replace('data:image/png;base64,', ''), {encoding: FileSystem.EncodingType.Base64}).then(res => {
// console.log(res);
// FileSystem.getInfoAsync(path, {size: true, md5: true}).then(file => {
FileSystem.getInfoAsync(path).then(file => {
console.log(file);
this.setState({ singleFileSIGN: file.uri});
console.log(singleFileSIGN)
})
}).catch(err => {
console.log("err", err);
})
};
handleEmpty () {
console.log('Empty');
};
handleClear () {
console.log('clear success!');
};
handleEnd () {
ref.current.readSignature();
};
render () {
return (
<View style={styles.container}>
<View style={{flex: 1, width:355,
...Platform.select({
android: {
marginBottom:-80,
borderColor: '#FF8C00',
borderWidth:1
// marginBottom:-150
},
}),
}}>
<SignatureScreen style={{height: '400%'}}
ref={this.ref}
onEnd={this.handleEnd}
onOK={this.handleSignature}
onEmpty={this.handleEmpty}
onClear={this.handleClear}
descriptionText={'Sign here!'}
/>
</View>
</View>
);
}
}

Hooks only used in function components. In class use like this:
constructor(props) {
super(props);
this.ref = React.createRef();
}

Related

undefined is not an object (evaluating 'FileSystem.EncodingType.Base64') in react native signature canvas react native fs

I am new to react native. I have react native signature canvas code. its working but when I draw signature then I am getting error like this = undefined is not an object (evaluating 'FileSystem.EncodingType.Base64'). please help. whats wrong with my code.
here is code
export default class Kyc extends Component {
constructor(props) {
super(props);
this.state = {
singleFileSIGN:''
};
this.ref = React.createRef();
}
handleSignature = signature => {
const path = FileSystem.cacheDirectory + 'sign.png';
FileSystem.writeAsStringAsync(path, signature.replace('data:image/png;base64,', ''), {encoding: FileSystem.EncodingType.Base64}).then(res => {
// console.log(res);
// FileSystem.getInfoAsync(path, {size: true, md5: true}).then(file => {
FileSystem.getInfoAsync(path).then(file => {
console.log(file);
this.setState({ singleFileSIGN: file.uri});
console.log(singleFileSIGN)
})
}).catch(err => {
console.log("err", err);
})
};
handleEmpty = ()=> {
console.log('Empty');
};
handleClear= ()=> {
console.log('clear success!');
};
handleEnd= ()=> {
this.ref.current.readSignature();
};
render () {
return (
<View style={styles.container}>
<View style={{flex: 1, width:355,
...Platform.select({
android: {
marginBottom:-80,
borderColor: '#FF8C00',
borderWidth:1
// marginBottom:-150
},
}),
}}>
<SignatureScreen style={{height: '400%'}}
ref={this.ref}
onEnd={this.handleEnd}
onOK={this.handleSignature}
onEmpty={this.handleEmpty}
onClear={this.handleClear}
descriptionText={'Sign here!'}
/>
</View>
</View>
);
}
}
please ignore this. I am new to react native. I have react native signature canvas code. its working but when I draw signature then I am getting error like this = undefined is not an object (evaluating 'FileSystem.EncodingType.Base64'). please help. whats wrong with my code.

How to convert react native signature canvas functional component to class component

I am new to react native. I do not know how to convert Functional component to class component. please help. here is my code of react native signature canvas code which is in functional component I want to convert it to class component please help thanks.
const ref = useRef();
const handleSignature = signature => {
const path = FileSystem.cacheDirectory + 'sign.png';
FileSystem.writeAsStringAsync(path, signature.replace('data:image/png;base64,', ''), {encoding: FileSystem.EncodingType.Base64}).then(res => {
// console.log(res);
// FileSystem.getInfoAsync(path, {size: true, md5: true}).then(file => {
FileSystem.getInfoAsync(path).then(file => {
console.log(file);
setSingleFileSIGN({ singleFileSIGN: file.uri});
console.log(singleFileSIGN)
})
}).catch(err => {
console.log("err", err);
})
};
const handleEmpty = () => {
console.log('Empty');
};
const handleClear = () => {
console.log('clear success!');
};
const handleEnd = () => {
ref.current.readSignature();
};
<View style={{flex: 1, width:355,
...Platform.select({
android: {
marginBottom:-80,
borderColor: '#FF8C00',
borderWidth:1
// marginBottom:-150
},
}),
}}>
<SignatureScreen style={{height: '400%'}}
ref={ref}
onEnd={handleEnd}
onOK={handleSignature}
onEmpty={handleEmpty}
onClear={handleClear}
descriptionText={'Sign here!'}
/>
</View>
const signatureRef = createRef()
clearSignature = async () => {
await signatureRef.current?.clearSignature()
}
handleOK = async (signature) => {
const sign = signature.split(",").pop()
await this.setState({
signatureVal: sign
})
// onOK(signature); // Callback from Component props
};
handleEnd = async () => {
await this.setState({isScrollEnabled: true})
await signatureRef.current?.readSignature()
}
render(){
<View>
<SignatureScreen
ref={signatureRef}
onOK={this.handleOK}
onEnd={this.handleEnd}
androidHardwareAccelerationDisabled={true}
onBegin={async () => {await this.setState({
isScrollEnabled: false
})}}
/>
</View>
}

React Native: Getting data from Firebase

I'm simply trying to retrieve data from the database in Firebase, and here's what I've got
var userList = [];
firebase.database()
.ref('/users/')
.once('value')
.then(snapshot => {
snapshot.forEach((doc) => {
userList.push(doc.val());
});
});
console.log(userList);
Even though I copy and pasted this code from a tutorial, the userList is empty outside of the snapshot. Can you tell me why that is?
The request to firebase is asynchronous so console.log(userList); is called before userList.push(doc.val()); gets called.
You should make userList a component state variable so that when you update it your component will re render.
Something like the following should work:
class UserListComponent extends Component {
constructor(props) {
super(props);
this.state = {
userList: [],
};
}
componentDidMount() {
this.getUsers();
}
getUsers() {
firebase
.database()
.ref('/users/')
.once('value')
.then((snapshot) => {
snapshot.forEach((doc) => {
this.setState({
userList: [...this.state.userList, doc.val()],
});
});
});
}
render() {
return (
<View>
{this.state.userList.map((item) => {
return (
<View>
<Text>{item.name}</Text>
</View>
);
})}
</View>
);
}
}

How can I update a variable after render?

Hi this is my code in App.js
var music = {
name: "Starboy",
artist: "The Weeknd",
albumArt: "",
length: "4:20",
audioURL:"",
};
export default class App extends Component
{
render() {
return (
<Image style={styles.albumArt} source={{ uri:music.albumArt }} />
);
}
};
I have another function in lastFM.js
export function getAlbumArt(albumName)
{
fetch('http://ws.audioscrobbler.com/2.0/?method=album.search&album='+albumName+'&api_key=MY_API_KEY&format=json&limit=1')
.then((response) => response.json())
.then((result) => {
const image = result.results.albummatches.album[0].image[2]['#text'];
console.log(image);
return image;
})
.catch((error) => {
console.log("ERROR: "+error);
});
}
How can I update music.albumArt in App.js and re-render Image inside App.js Render?
This might help. Re-render happens when you change the state of the component. So, here we are updating the state once we get data from the API.
export default class App extends React.Component {
constructor() {
super();
this.state = {
name: "Starboy",
artist: "The Weeknd",
albumArt: "",
length: "4:20",
audioURL: ""
};
}
componentDidMount(){
fetch('http://ws.audioscrobbler.com/2.0/?method=album.search&album='+albumName+'&api_key=MY_API_KEY&format=json&limit=1')
.then((response) => response.json())
.then((result) => {
const image = result.results.albummatches.album[0].image[2]['#text'];
console.log(image);
this.setState({...this.state, albumArt: image });
})
.catch((error) => {
console.log("ERROR: "+error);
});
}
render() {
return <Image style={styles.albumArt} source={{ uri: this.state.albumArt }} />;
}
}

react native modal not close after setState false

I have set modal visibility to false but it still showing. I cant figure out what causes this issue. this my code at loading.js.
I'm use this component in main what happen when setState false but its just close after close simolator and restart the device
import React,{Component} from 'react';
import PropTypes from 'prop-types'
import {View, Image, Modal, StyleSheet, Text} from "react-native";
export default class Loader extends Component{
render(){
const {animationType,modalVisible}=this.props;
return(
<Modal
animationType={animationType}
transparent={true}
visible={modalVisible}>
<View style={styles.wrapper}>
<View style={styles.loaderContainer}>
<Image
source={require('../img/loading.gif')}
style={styles.loaderImage}/>
</View>
</View>
</Modal>
)
}
}
Loader.propTypes={
animationType:PropTypes.string.isRequired,
modalVisible:PropTypes.bool.isRequired
}
this main class
export default class ForoshRah extends Component {
constructor() {
super();
I18nManager.forceRTL(true);
this.state = {
image: null,
images: null,
loadingVisible:false,
};
this.onValueChange2=this.onValueChange2.bind(this);
this.OnSubmiteData=this.OnSubmiteData.bind(this);
}
onValueChange2(value: string) {
this.setState({
Field: value,
});
}
async OnSubmiteData(){
this.setState({loadingVisible:true})
let token = await AsyncStorage.getItem('token',token);
let response = await
fetch(url,{
method:'POST',
headers:{
'Content-Type':'application/json',
Authorization:'JWT'+" "+token,
}
,body: JSON.stringify({
title,
})
})
let register = await response.json();
this.setState({userID:register.id})
if(response.status===200){
this.UploadImage()
}
}
async UploadImage() {
let token = await AsyncStorage.getItem('token',token);
let response = await fetch(url,{
method:'POST',
headers:{
Authorization:'JWT'+" "+token,
},body: formData
})
let uimage = await response;
console.log('user',this.state.userID);
if(response.status=200){
handleCloseModal = () => {
console.log(this.state.loadingVisible);
this.setState({ loadingVisible: false})
});
};
this.props.navigation.dispatch({ type: 'Navigation/BACK' })
}else {
setTimeout(() => {
this.setState({ loadingVisible: false })
}, 100)
}
setTimeout(() => {
this.setState({ loadingVisible: false })
}, 100)
}
render() {
return (
<KeyboardAwareScrollView >
<View style={{marginBottom:'10%'}}>
<Button block style={{backgroundColor:'#8e25a0'}} onPress={this.OnSubmiteData.bind(this)}>
</Button>
</View>
<Loader
modalVisible={loadingVisible}
animationType="fade"
/>
</KeyboardAwareScrollView>
);
}
}
onsubmitdata setState true and after response going to 200 Setstate set false in code main
You cannot just call state name as you have did. You should do like below.
<Loader
modalVisible={this.state.loadingVisible}
animationType="fade"
/>