React-redux action is returning before async action is complete - react-native

I have a React Native app using redux and I'd like my action to set the GPS coordinates so I have them available in the store. You can see my console logs in the code, and 'action returning' is logged before 'has coordinates', which is the problem.
Component:
<TouchableOpacity style={{flex:1}} onPress={() => {
this.props.setLocation();
}}>
Action.js
export function setLocation(){
let coords = {
latitude:0,
longitude:0,
navigatorError:''
};
navigator.geolocation.getCurrentPosition(
(position) => {
console.log('has coordinates');
coords['latitude'] = position.coords.latitude
coords['longitude'] = position.coords.longitude
coords['navigatorError'] = null
},
(error) => coords['navigatorError'] = error.message,
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
console.log('action returning');
return {
type: 'set_location',
payload: coords
};
};
Reducer.js
export default (state = null, action) => {
switch(action.type){
case 'set_location':
return action.payload;
default:
return state;
}
}
Note: I'm not actually using redux-thunk in this project, I'm not sure if it's appropriate for what I need here.

You can use async and await to accomplish this. Basically, you need to await the coords to be returned from your asynchronous call.
Something like this:
export async function setLocation(){
let coords = {
latitude:0,
longitude:0,
navigatorError:''
};
await navigator.geolocation.getCurrentPosition(
(position) => {
console.log('has coordinates');
coords['latitude'] = position.coords.latitude
coords['longitude'] = position.coords.longitude
coords['navigatorError'] = null
},
(error) => coords['navigatorError'] = error.message,
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
console.log('action returning');
return {
type: 'set_location',
payload: coords
};
};
Documentation on async/await can be found here.

Related

Why location permission pop up not showing in React Native?

I want to implement get current location in react native. I put permission to activate location if location is not activate in phone before calling geolocation API but pop up not showing and this PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,{ title: 'Location Access Required', message: 'This App needs to Access your location'},); always return "granted" when request permission using PermissionAndroid module.
this is my code
import { PermissionsAndroid } from 'react-native';
import Geolocation from '#react-native-community/geolocation';
...
componentDidMount(){
const requestLocationPermission = async () => {
let geoOptions = {
enableHighAccuracy: true,
timeout:20000,
maximumAge: 60*60*24
}
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Access Required',
message: 'This App needs to Access your location',
},
);
console.warn(granted);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(this.geoLocationSuccess,this.geoLocationFailure,geoOptions);
}
} catch (err) {
console.warn(err);
}
};
requestLocationPermission();
}
is my implementation is wrong ? because i want to show pop up when location service is not enable to let user enable it
This may be of little help, first make sure no library location other than react-native-geolocation-service. then if there is no use react hook. you might try this method below.
hasLocationPermission = async () => {
const hasPermission = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (hasPermission === PermissionsAndroid.RESULTS.GRANTED) {
console.log('lagi req permission');
return true;
}
const status = await PermissionsAndroid.check(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
);
if (status) {
console.log('permission diberikan');
return true;
}
if (status === PermissionsAndroid.RESULTS.DENIED) {
ToastAndroid.show(
'Location permission denied by user.',
ToastAndroid.LONG,
);
} else if (status === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
ToastAndroid.show(
'Location permission revoked by user.',
ToastAndroid.LONG,
);
}
return false;
};
async componentDidMount() {
if (await this.hasLocationPermission()) {
Geolocation.getCurrentPosition(
position => {
console.log('posisi ditemukan',position.coords.latitude, position.coords.longitude);
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
this.goToRegion(position.coords.latitude, position.coords.longitude);
},
error => {
Alert.alert(
'Oopss!',
error.message,
[
{
text: 'OK',
onPress: () => console.log('Cancel Pressed'),
},
],
);
console.log(error.message);
this.setState({error: error.message});
},
{
accuracy: {
android: 'high',
ios: 'best',
},
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 10000,
distanceFilter: 0,
forceRequestLocation: true,
forceLocationManager: false,
showLocationDialog: true,
},
);
}
}

React Native AsyncStorage.getItem is not working. ({"_40": 0, "_55": null, "_65": 0, "_72": null})

Good day! I have this function of AsyncStorage that gets an item of a token. I used with ApolloClient to process the token but when I test it first, it seems to have an error with what will I get by AsyncStorage function.
export function jwtLogin(data) {
return async dispatch => {
const userData = {
email: data.email,
password: data.password,
};
console.log(userData);
const client = new ApolloClient({
link: new HttpLink({
uri: API_URL,
}),
cache: new InMemoryCache(),
});
client
.mutate({
mutation: loginUser,
variables: {
email: userData.email,
password: userData.password,
},
})
.then(resp => {
console.log(resp.data.tokenCreate);
console.log('Token', resp.data.tokenCreate.token);
if (resp.data.tokenCreate.token !== null) {
saveJWTTokenData(resp.data.tokenCreate.token); //from AsyncStorage save function
async function main() { //function of AsyncStorage
await AsyncStorage.getItem('jwt_token').then(item => {
return item;
});
}
console.log(main()); // returns error
Actions.push('main_loading');
} else {
const errors = resp.data.tokenCreate.errors;
{
errors.map(err => {
Alert.alert('Error.', err.message);
});
}
}
})
.catch(err => {
Alert.alert('Error.', err.message);
});
};
}
For the save storage function:
export const saveJWTTokenData = async jwt_token => AsyncStorage.setItem('jwt_token', jwt_token);
My Error Log Picture
I think your Promise is not handled correctly..
Try to add a catch after your then call like this:
.catch(err => console.log(err))
Or try to use your function like this maybe:
await getData("jwt_token")
.then(data => data)
.then(value => this.setState({ token: value })) // here it is setState but I guess you can also return
.catch(err => console.log("AsyncStorageErr: " + err));

react native async getting data when running app first time

I have two components, in first components storing data in asyncstorage, in second component display data, when install app and save data does not get data from asyncstorage, when open app second time data are displayed.
storeData = async (item, messave, messrem) => {
const checkarary = this.state.favorite;
if(checkarary.some(e => e.name === item.name)) {
const value = this.state.favorite;
const position = value.filter((lists) => lists.id !== item.id);
this.setState({
favorite: position
}, () => {
try {
AsyncStorage.setItem('favoriti', JSON.stringify(this.state.favorite), () => {
Toast.show({
text: messrem,
buttonText: "Okay",
duration: 3000,
type: "danger"
});
});
} catch (error) {
}
});
} else {
this.setState({
favorite: [...this.state.favorite, item]
}, () => {
try {
AsyncStorage.setItem('favoriti', JSON.stringify(this.state.favorite), () => {
// AsyncStorage.getItem('favoriti', (err, result) => {
// console.log(result);
// });
Toast.show({
text: messave,
buttonText: "Okay",
duration: 3000,
type: "success"
});
});
} catch (error) {
}
});
}
};
Getting data in second component
_retrieveData = async () => {
try {
AsyncStorage.getItem('favoriti').then((value) => {
const parsed = JSON.parse(value);
this.setState({ favorite: parsed })
})
} catch (error) {
}
};
componentDidMount() {
this._retrieveData();
setTimeout(() => {
this.setState({
loading: false,
})
}, 2000)
};
componentDidUpdate() {
this._retrieveData();
};
How fix this issue, is there some solution. Can I set Item and reload app when install app or somthing else.
Use this
componentWillMount() {
this._retrieveData();
setTimeout(() => {
this.setState({
loading: false,
})
}, 2000)
};
instead of
componentDidMount() {
this._retrieveData();
setTimeout(() => {
this.setState({
loading: false,
})
}, 2000)
};
As componentWillMount is called after constructor is called for class and componentDidMount is called after screen is once rendered.

How to create component in render part from fetched API?

I'm trying to fetch data from api and I used componentDidMount lifecycle for that, But I have a list in my view which need to be created from that API, so I use map function for received data to get all items and show in render part, But when I run my code I get
this.state.matchInfo.map in not a function
Please help me to solve this problem, I knew that componentDidMount will run after first render so I create an empty state first and hoped that after fetching data, component will render again and will show my data. but it keeps getting me the error
here is my code:
constructor(props) {
super(props);
this.state = {
userName: '',
userToken: '',
userID: '',
firstTime: true,
loading: true,
showAlert : false,
alertType : true,
alertMessage : '',
animatedMatchBtn : new Animated.Value(1),
matchInfo: []
};
}
componentDidMount() {
this._bootstrapAsync(true);
}
_bootstrapAsync = async (timeOutStat = null) => {
const userToken = await AsyncStorage.getItem('userToken');
const userName = await AsyncStorage.getItem('userName');
const userID = await AsyncStorage.getItem('userID');
await this.setState({
userName: userName,
userToken: userToken,
userID: userID,
})
if(timeOutStat) {
this.timeOut = setTimeout(() => {
this.setState({
loading: false,
showAlert: true,
alertType: true,
alertMessage: ErrorList.matchMakingError
});
}, 20000)
}
console.log('token', userToken)
await fetch(getInitUrl('getMatchInfo','',this.props.navigation.getParam('matchID', 0)), {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization : `Bearer ${userToken}`
}
}).then(response => Promise.all([response.ok, response.status ,response.json()]))
.then(([responseOk,responseStatus, body]) => { //
this.setState({loading : false});
clearTimeout(this.timeOut);
if (responseOk) {
console.log('match Info', body);
this.setState({
matchInfo : body
})
} else {
console.log(responseStatus, body);
this.setState({
showAlert : true,
alertType : true,
alertMessage : ErrorList[body.tag]
});
}
})
.catch(error => {
console.error(error);
});
};
render() {
//console.log(puzzleSizes)
let rows = this.state.matchInfo.map((item , index)=>{
return
<MatchDetailBox
/>
})
console.log(rows)
<View>
{rows}
</View>
}
Even though this.setState() is asynchronous, it's not promisified hence it wont't work using promise's .then() or its syntactic sugar async/await. So there's no use for await in front of it. But I guess it creates a one tick delay.
Also why do you have await in front of fetch() and also .then() after that. Shouldn't either of them do?
The error this.state.matchInfo.map is not a function would occur only when this.state.matchInfo is not an array but you have initialized it to be one, so at any point of time matchInfo gets modified it must be becoming non-array like an object or something which doesn't have a native .map().
Have you checked response coming from API? I hope this helps.
this.setState({ matchInfo: body });
mapData = () => {
this.state.matchInfo.map((item , index)=>{
return(
<View>
<MatchDetailBox />
<View>
{item}
</View>
</View>
)
})
}
render() {
return {this.mapData()}
}

Pusher chatKit onMessage hook fails in Expo app

I am using React Native with Expo, and I am able to create users + rooms and send messages to them with the following code:
const hooks = {
onMessage: message => {
console.log("message", message);
this.setState({
messages: [...this.state.messages, message]
});
},
onUserStartedTyping: user => {
this.setState({
usersWhoAreTyping: [...this.state.usersWhoAreTyping, user.name]
});
},
onUserStoppedTyping: user => {
this.setState({
usersWhoAreTyping: this.state.usersWhoAreTyping.filter(
username => username !== user.name
)
});
},
onPresenceChange: () => this.forceUpdate()
};
class SetupChatKit extends React.Component {
constructor(props) {
super(props);
this.state = {
chatManager: null,
currentUser: {},
currentRoom: {},
messages: [],
usersWhoAreTyping: []
};
}
componentDidMount() {
const { userId, name } = this.props;
this.instantiateChatManager(userId);
this.createChatKitUser({ userId, name });
}
joinOrCreateChatKitRoom = (mode, chatKitRoomId, title) => {
const { chatManager } = this.state;
return chatManager
.connect()
.then(currentUser => {
this.setState({ currentUser });
if (mode === "join") {
return currentUser.joinRoom({ roomId: chatKitRoomId, hooks });
}
return currentUser.createRoom({
name: title,
private: false,
hooks
});
})
.then(currentRoom => {
this.setState({ currentRoom });
return currentRoom.id;
})
.catch(error => console.error("error", error));
};
instantiateChatManager = userId => {
const chatManager = new Chatkit.ChatManager({
instanceLocator: "v1:us1:9c8d8a28-7103-40cf-bbe4-727eb1a2b598",
userId,
tokenProvider: new Chatkit.TokenProvider({
url: `http://${baseUrl}:3000/api/authenticate`
})
});
this.setState({ chatManager });
};
My problem is that console.log("message", message); never gets called, even when I manually add messages to the room via the online control panel.
I've tried logging from chatManager, and that looks like the following:
As you can see from the documentation, the onMessage hook needs to be attached on subscribeRoom, not when joining a room.
https://docs.pusher.com/chatkit/reference/javascript#connection-hooks
So probably add subscribeToRoom() after the first success promise in your joinOrCreateChatKitRoom() method.
I refactored the code with async/await and used .subscribetoRoom() like so:
joinOrCreateChatKitRoom = async (mode, chatKitRoomId, title) => {
const { chatManager } = this.state;
try {
const currentUser = await chatManager.connect();
this.setState({ currentUser });
let currentRoom;
if (mode === "join") {
currentRoom = await currentUser.joinRoom({
roomId: chatKitRoomId
});
} else {
currentRoom = await currentUser.createRoom({
name: title,
private: false
});
}
this.setState({ currentRoom });
await currentUser.subscribeToRoom({
roomId: currentRoom.id,
hooks: {
onMessage: message => {
this.setState({
messages: [...this.state.messages, message]
});
},
onUserStartedTyping: user => {
this.setState({
usersWhoAreTyping: [...this.state.usersWhoAreTyping, user.name]
});
},
onUserStoppedTyping: user => {
this.setState({
usersWhoAreTyping: this.state.usersWhoAreTyping.filter(
username => username !== user.name
)
});
},
onPresenceChange: () => this.forceUpdate()
}
});
return currentRoom.id;
} catch (error) {
console.error("error creating chatManager", error);
}
};