I am new to React Native. In my app, the same function to check if user exists in the database is used in 3 different files.
checkUserExists = (userId) => {
var that = this;
database.ref('users').child(userId).once('value').then(function(result){
const exists = (result.val() !== null);
if (exists) {
var data = result.val();
that.setState({
username: data.username,
name: data.name
})
}
})
}
To reduce amount of code, I want to put this function into a component so that it can be reused. So I created a new file with this function:
export function checkUserExists (userId) {
database.ref('users').child(userId).once('value').then(function(result){
const exists = (result.val() !== null);
if (exists) {
var data = result.val();
setState({
username: data.username,
name: data.name
})
}
})
}
But this is met with [Unhandled promise rejection: ReferenceError: Can't find variable: setState]
What is the proper way to handle this? Do I have to use Redux? I can't find a clear answer on SO so far.
Update: I also tried
export default class Authentication extends Component {
checkUserExists = (userId) => {
database.ref('users').child(userId).once('value').then(function(result){
const exists = (result.val() !== null);
if (exists) {
var data = result.val();
setState({
username: data.username,
name: data.name
})
}
})
}
}
and I tried to call it like
Authentication.checkUserExists(user.id);
but gets: TypeError: _authentication.default.checkUserExists is not a function