React Native Redux: props not updating after API call - android

I am quite new to React / React Native / Redux so I feel I am doing something wrong.
The problem
I want to show a spinner while an API is called, and an error message once this API call fails. Props are not updating, and so the components don't show the desired message or spinner
The code (only the relevant chunks)
The component
class Home extends Component {
componentWillMount() {
this.props.tokenGet();
}
renderSpinner() {
if (this.props.loading) {
return (
<Spinner size="large" />
);
}
return null;
}
renderMessage() {
if (this.props.message) {
return (
<Text style={{flex: 1, background: red, color: black}}>
{ this.props.message }
</Text>
)
}
return null;
}
render() {
return (
{ this.renderSpinner() }
{ this.renderMessage() }
)
}
}
const mapStateToProps = (state) => {
const { auth } = state;
const {
loading,
token,
message
} = auth || {
loading: false,
token: null,
message: null
};
return {
loading,
token,
message
}
};
export default connect(mapStateToProps, { tokenGet } )(Home);
The action creator
export const tokenGet = () => {
return (dispatch) => {
dispatch({ type: 'TOKEN_GET_START'});
// Perform the actual API call
let requestToken = fetch(apiBaseUrl + "/tokens", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(.....)
});
Promise
.race([timeout, requestToken])
.then((response) => response.json())
.then((responseJson) => {
... not relevant ...
})
.catch((error) => {
dispatch({ type: 'TOKEN_GET_FAIL', payload: error});
});
The timeout function, which gets called when the server fails to respond
let timeout = new Promise((resolve, reject) => {
setTimeout(reject, 2000, 'Request timed out. Please check your internet connection.');
});
The reducer
import {
TOKEN_GET_START,
TOKEN_GET_SUCCESS,
TOKEN_GET_FAIL
} from '../actions/types';
const INITIAL_STATE = {
loading: false,
token: null,
message: null
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case TOKEN_GET_START:
return { ...state, loading: true };
case TOKEN_GET_SUCCESS:
return { ...state, loading: false, token: action.payload };
case TOKEN_GET_FAIL:
return { ...state, loading: false, message: action.payload };
default:
return state;
}
};
The combined reducers
import { combineReducers } from 'redux';
import AuthReducer from './AuthReducer';
export default combineReducers({
auth: AuthReducer
});
The actual behavior is that the props don't change and no message or spinner is visible. With some console logs I know that the API call ends because of the timeout. I am not sure if the state gets updated properly though. I don't know in at which point I can console log this.

It turned out to be because of the quotes in 'TOKEN_GET_FAIL'
That is a string and not the const I need. So I changed to TOKEN_GET_FAIL and it works.

Related

React Native BLE Manager (Android) status code 14 on write to characteristic

I'm using the react native ble manager package to build a react native app that communicates with a python client over BLE.
When writing to a characteristic on Android (this bug does not seem to appear on IOS) the write is successful but shortly after it I receive this error:
ERROR Error writing eeee2a38-0000-1000-8000-00805f9b34fb status=14
This is the simplified code that handles connecting, notifications and writing on the Android side:
import { NativeModules, NativeEventEmitter, Platform } from 'react-native'
import BleManager, { Peripheral } from 'react-native-ble-manager'
import { END } from 'redux-saga'
import { bytesToString } from 'convert-string'
const UPDATE_SERVICE_UUID = '0000180d-aaaa-1000-8000-00805f9b34fb'
export const Characteristic =
{
WIFI_STATUS_UUID: 'bbbb2a38-0000-1000-8000-00805f9b34fb',
WIFI_CREDS_UUID: 'aaaa2a38-0000-1000-8000-00805f9b34fb',
VERSION_UUID: 'cccc2a38-0000-1000-8000-00805f9b34fb',
UPDATE_STATUS_UUID: 'dddd2a38-0000-1000-8000-00805f9b34fb',
DO_UPDATE_UUID: 'eeee2a38-0000-1000-8000-00805f9b34fb',
ERROR_UUID: 'ffff2a38-0000-1000-8000-00805f9b34fb',
}
class BLEManager {
bleManagerModule: any
bleManagerEmitter: any
scanning: boolean
dispatch: any
stopScanListener: any
peripheralDiscoverListener: any
characteristicUpdateListener: any
onDisconnectListener: any
connectTimeout: any
constructor() {
BleManager.start({ showAlert: false })
this.bleManagerModule = NativeModules.BleManager
this.bleManagerEmitter = new NativeEventEmitter(this.bleManagerModule)
this.scanning = false
}
startScan = (onPeripheralFound: (peripheral: Peripheral | null) => void) => {
if (!this.scanning) {
BleManager.scan([], 3, true)
.then(() => {
console.log('Scanning...')
this.scanning = true
this.peripheralDiscoverListener = this.bleManagerEmitter.addListener(
'BleManagerDiscoverPeripheral',
onPeripheralFound,
)
this.stopScanListener = this.bleManagerEmitter.addListener(
'BleManagerStopScan',
() => {
onPeripheralFound(END)
},
)
return
})
.catch(err => {
console.error(err)
})
} else {
console.log('already scanning')
}
return () => {
console.log('stopped scanning')
this.peripheralDiscoverListener.remove()
this.stopScanListener.remove()
}
}
getBondedDevices = (onGetBondedPeripherals: any) => {
BleManager.getBondedPeripherals().then(bondedPeripheralsArray => {
onGetBondedPeripherals(bondedPeripheralsArray)
// TODO: is the END message here necessary?
onGetBondedPeripherals(END)
return
})
return () => {}
}
connectToPeripheral = async (peripheralID: string) => {
try {
await new Promise(async (resolve, reject) => {
this.connectTimeout = setTimeout(reject, 3000)
console.log('connecting to ' + peripheralID)
try {
await BleManager.connect(peripheralID)
await BleManager.retrieveServices(peripheralID)
} catch (error) {
reject()
}
if (this.connectTimeout) {
clearTimeout(this.connectTimeout)
this.connectTimeout = null
this.onDisconnectListener = this.bleManagerEmitter.addListener(
'BleManagerDisconnectPeripheral',
this.onDisconnectPeripheral,
)
resolve()
}
})
} catch (err) {
clearTimeout(this.connectTimeout)
this.connectTimeout = null
console.error('Could not connect to device.')
throw new Error(err)
}
return
}
watchForCharacteristicsUpdates = async (
updateCharValue: (arg0: { payload: any }) => void,
peripheralID: string,
) => {
try {
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.ERROR_UUID,
)
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.VERSION_UUID,
)
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.UPDATE_STATUS_UUID,
)
} catch (e) {
updateCharValue(new Error(e))
console.error(e)
}
console.log('watch for notifications')
this.characteristicUpdateListener = this.bleManagerEmitter.addListener(
'BleManagerDidUpdateValueForCharacteristic',
({ value, characteristic }) => {
// Convert bytes array to string
const data = bytesToString(value)
console.log(
`Received ${data} (${value}) for characteristic ${characteristic}`,
)
updateCharValue({
payload: {
characteristic: characteristic,
data: data,
},
})
},
)
}
disconnectFromPeripheral = async (peripheralID: string) => {
await BleManager.disconnect(peripheralID)
this.characteristicUpdateListener.remove()
}
onDisconnectPeripheral = (peripheralID: string) => {
console.log(peripheralID + ' disconnected')
this.onDisconnectListener.remove()
}
checkIfConnected = async (peripheralID: string) => {
return await BleManager.isPeripheralConnected(peripheralID, [])
}
triggerUpdateCheck = async (peripheralID: string) => {
return await BleManager.write(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.WIFI_STATUS_UUID,
[1],
)
}
runUpdate = async (peripheralID: string) => {
return await BleManager.write(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.DO_UPDATE_UUID,
[1],
)
}
}
const bleManager = new BLEManager()
export default bleManager
I've researched this a bit and it seems that some people have the problem but I could not find an explanation or solution to it.
I'm even unsure where to start debugging. Any suggestions are welcome.
Details:
Device: [Pixel 6]
OS: [Android 12]
react-native-ble-manager version: ^8.4.1
react-native version: 0.67.4
Note: I've also asked this question on Github: https://github.com/innoveit/react-native-ble-manager/issues/887
The problem (as mentioned by Martijn) was the bug in Bluez which is fixed in 5.65. Simply upgrading and clearing the Bluetooth cache fixed it.

MediaPositionState shows incorrect currentTime

So, here is the problem. I'm using audio html5 element in my react project.
The typical flow for problem is:
the song is playing.
User presses pause on some time(let's say that time is 1.20).
User locks the phone.
After several minutes user unlocks his phone, presses "Play" button and here what happens:
The mediaPositionState count current time as previous(1.20) PLUS current time of the audio, instead of counting just current.
This extra 1.20 is remaining even when changing songs.
I've tried to control it in useEffect below
useEffect(() => {
const audioEl = audioRef.current;
if (audioEl) {
audioEl.addEventListener('timeupdate', updateTime);
audioEl.addEventListener('loadeddata', updatePositionState);
}
return () => {
if (audioEl) {
audioEl.removeEventListener('timeupdate', updateTime);
audioEl.removeEventListener('loadeddata', updateTime);
updatePositionState();
}
};
}, []);
but it works normally only when user is in focus with audio.
Also I have following code:
function updatePositionState() {
if (navigator.mediaSession?.setPositionState) {
navigator.mediaSession.setPositionState({
duration: audioRef.current?.duration ?? 0.0,
position: audioRef.current?.currentTime ?? 0.0,
});
}
}
const createMediaSession = (state: AudioStateType) => {
if (navigator.mediaSession) {
navigator.mediaSession.metadata = new MediaMetadata({
title: state.currentSongName,
artist: state.currentArtistName,
album: state.currentAlbumName,
artwork: [
{
sizes: '300x300',
src: `http://storage.musicstream.app/cover/${state.currentAlbumCoverId}`,
},
],
});
navigator.mediaSession.setActionHandler('play', function () {
dispatch({ type: 'resume' });
updatePositionState();
});
navigator.mediaSession.setActionHandler('pause', function () {
dispatch({ type: 'pause' });
updatePositionState();
});
navigator.mediaSession.setActionHandler('seekto', function (details) {
dispatch({ type: 'manual_update_time', time: details.seekTime });
updatePositionState();
});
navigator.mediaSession.setActionHandler('previoustrack', () => {
return 0;
});
navigator.mediaSession.setActionHandler('nexttrack', () => {
return 0;
});
}
};
I don't know how to normally describe the problem, let's assume that mediaposition messes up when user swipes out the MediaSession notification.
I will provide more code if you ask.
Also I provide the screenshots(despite I tried to force the problem similar one occured: it shows time as the end of track).
current song time
current song time is okay when paused
current song time is messed when playing
Adding updateTime function by request
It is just for updating state in react.Context
const updateTime = () => {
if (audioRef.current) {
dispatch({ type: 'update_time', time: audioRef.current.currentTime });
}
};
Also, the full reducer looks like this(I don't think it would be helpful):
function audioReducer(state: AudioStateType, action: Action): AudioStateType {
switch (action.type) {
case 'fetch_and_play': {
play(action.songData?.currentSongId).then(() => {
dispatch({
type: 'play',
songData: {
...action.songData,
length: audioRef.current?.duration,
},
});
});
return state;
}
case 'play': {
createMediaSession({ ...state, ...action.songData });
return { ...state, ...action.songData };
}
case 'pause': {
pause();
return { ...state, songIsPaused: true };
}
case 'resume': {
resume();
return { ...state, songIsPaused: false };
}
case 'update_time': {
return { ...state, currentTime: action.time };
}
case 'manual_update_time': {
if (audioRef.current) {
audioRef.current.currentTime = action.time;
return { ...state, currentTime: action.time };
} else {
return state;
}
}
default: {
return state;
}
}
}
I made a codesandbox, where you can see my problem. https://codesandbox.io/s/wizardly-wiles-87qi1?file=/src/App.js
In order to truly understand please use an android phone
Reducer should be Pure function, use action before reducer for dispatch and other staff:
Action.ts
const fetchAndPlay = (currentSongId) => {
play(currentSongId).then(() => {
createMediaSession({ ...state, ...action.songData });
dispatch({
type: 'play',
//just pass data u need to show or you want rerender them
length: audioRef.current?.duration,
});
});
}
Reducer.ts
function audioReducer(state: AudioStateType, action: Action): AudioStateType {
switch (action.type) {
case 'play':
return { ...state, length:action.length, playing: true};
...
}
In your component just call this action :
fetchAndPlay(songId)

React Native Router flux action.key() doesn't work

I am building a project on React Native, I am new to React Native. But unfortunately the Actions.key() not working. Here is my code details
App.js
import React, { Component } from 'react';
import { AsyncStorage, ActivityIndicator } from 'react-native';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import { PersistGate } from 'redux-persist/integration/react'
import Spinner from './components/common/Spinner';
import reducers from './reducers';
import Router from './Router';
import { persistStore, persistReducer } from 'redux-persist'
class App extends Component {
render() {
renderLoading = () =>
{
<Spinner size="large" />;
}
const persistConfig = {
key: 'root2',
storage: AsyncStorage
}
const persistedReducer = persistReducer(persistConfig, reducers)
const store = createStore(persistedReducer, {}, applyMiddleware(ReduxThunk));
const persistor = persistStore(store);
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Router />
</PersistGate>
</Provider>
);
}
}
export default App;
LoginForm.js
import React, { Component } from 'react';
import { Text } from 'react-native';
import { connect } from 'react-redux';
import { emailChanged, passwordChanged, loginUser, loginUserSuccess1 } from '../actions';
import { Card, CardSection, Input, Button, Spinner } from './common';
import { Actions } from 'react-native-router-flux';
import NameEnter from './NameEnter';
import Router from '../Router';
class LoginForm extends Component {
componentDidMount()
{
console.log (this.props.userDetails);
if(this.props.userDetails != null)
{
if (this.props.userDetails.success !== false) {
console.log (this.props.userDetails.success);
this.props.loginUserSuccess1(this.props.userDetails);
}
}
//Actions.screen1();
}
onEmailChange(text) {
this.props.emailChanged(text);
}
onPasswordChange(text) {
this.props.passwordChanged(text);
}
onButtonPress() {
const { email, password } = this.props;
this.props.loginUser({ email, password });
}
renderButton() {
// if (this.props.loading) {
// return <Spinner size="large" />;
// }
return (
<Button onPress={this.onButtonPress.bind(this)}>
Login
</Button>
);
}
render() {
return (
<Card>
<CardSection>
<Input
label="Email"
placeholder="email#gmail.com"
onChangeText={this.onEmailChange.bind(this)}
value={this.props.email}
/>
</CardSection>
<CardSection>
<Input
secureTextEntry
label="Password"
placeholder="password"
onChangeText={this.onPasswordChange.bind(this)}
value={this.props.password}
/>
</CardSection>
<Text style={styles.errorTextStyle}>
{this.props.error}
</Text>
<CardSection>
{this.renderButton()}
</CardSection>
</Card>
);
}
}
const styles = {
errorTextStyle: {
fontSize: 20,
alignSelf: 'center',
color: 'red'
}
};
const mapStateToProps = ({ auth }) => {
const { email, password, error, loading , userDetails } = auth;
return { email, password, error, loading , userDetails };
};
export default connect(mapStateToProps, {
emailChanged, passwordChanged, loginUser, loginUserSuccess1
})(LoginForm);
AuthActions.js
import { Actions } from 'react-native-router-flux';
import axios from 'react-native-axios';
import {
EMAIL_CHANGED,
PASSWORD_CHANGED,
LOGIN_USER_SUCCESS,
LOGIN_USER_FAIL,
LOGIN_USER,
URL
} from './types';
export const emailChanged = (text) => {
return {
type: EMAIL_CHANGED,
payload: text
};
};
export const passwordChanged = (text) => {
return {
type: PASSWORD_CHANGED,
payload: text
};
};
export const loginUser = ({ email, password }) => {
return (dispatch) => {
dispatch({ type: LOGIN_USER });
axios.post(URL + '/hostLogin', {
email: email,
password: password
})
.then((user) => {
console.log(user.data);
loginUserSuccess(dispatch, user);
})
.catch((error) => {
loginUserFail(dispatch);
});
// firebase.auth().signInWithEmailAndPassword(email, password)
// .then(user => loginUserSuccess(dispatch, user))
// .catch((error) => {
// console.log(error);
// firebase.auth().createUserWithEmailAndPassword(email, password)
// .then(user => loginUserSuccess(dispatch, user))
// .catch(() => loginUserFail(dispatch));
// });
};
};
const loginUserFail = (dispatch) => {
dispatch({ type: LOGIN_USER_FAIL });
};
const loginUserSuccess = (dispatch, user) => {
dispatch({
type: LOGIN_USER_SUCCESS,
payload: user.data
});
Actions.main();
};
export const loginUserSuccess1 = (user) => {
console.log(1);
return {
type: 'Navigate',
payload: 'Success'
};
};
AuthReducer.js
import {
EMAIL_CHANGED,
PASSWORD_CHANGED,
LOGIN_USER_SUCCESS,
LOGIN_USER_FAIL,
LOGIN_USER
} from '../actions/types';
import { Actions } from 'react-native-router-flux';
const INITIAL_STATE = {
email: '',
password: '',
userDetails: null,
error: '',
loading: false
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case EMAIL_CHANGED:
return { ...state, email: action.payload };
case PASSWORD_CHANGED:
return { ...state, password: action.payload };
case LOGIN_USER:
return { ...state, loading: true, error: '' };
case LOGIN_USER_SUCCESS:
console.log(action.payload );
return { ...state, userDetails: action.payload };
case LOGIN_USER_FAIL:
return { ...state, error: 'Authentication Failed.', password: '', loading: false };
case 'Navigate':
console.log(2);
Actions.main();
default:
return state;
}
};
This is Router.js
import React from 'react';
import { Scene, Router, Actions } from 'react-native-router-flux';
import LoginForm from './components/LoginForm';
import NameEnter from './components/NameEnter';
const RouterComponent = () => {
return (
<Router>
<Scene key="root" hideNavBar>
<Scene key="auth" >
<Scene key="login" component={LoginForm} title="Please Login" />
</Scene>
<Scene key="main">
<Scene key="screen1" component={NameEnter} title="Please Enter Your Name " />
</Scene>
</Scene>
</Router>
);
};
export default RouterComponent;
Now in Authreducer.js i am using Actions.main() to navigate to main . But that is not working . Is something wrong with the settings of router . Please help
It is not working because you have mixed react native commands with redux. What i have noted is that redux always loads first before react native libraries etc loads so it will not work, you have to separate them to make them work.
You can separate them by returning true (also remove Actions.main() from redux file switch statements) and you will read this response from another file(this file will be react native component) where you can use Actions.main() and then it will work.
From the redux documentations:
"Given the same arguments, it [reducers] should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation."
Reducers should always stay pure. It's an antipattern to perform routing transitions inside a reducer.
Beside this: I had the same issue with react native 0.57.0 and react-native-router-flux v4, which is based on React Navigation v2.x. Every method except .key() was working, so I had to downgrade back to rnrf 4.0.0-beta.32. It doesn't seem to be a bug and is more likely caused by a dependency version mismatch (e.g. react & react-native). I will dig deeper into this issue and hopefully find a way to use the newer versions.

TypeError: _this2.setState is not a function, Cant bind state

I am getting this this error. As I am already using ES6 format, That arrow but also getting same error. And somewhat confuse that how to use bind. How can I get out of this error.
code:
async fetchData() {
const { navigate } = this.props.navigation;
var DEMO_TOKEN = await AsyncStorage.getItem(STORAGE_KEY);
NetInfo.isConnected.fetch().then((isConnected) => {
if ( isConnected )
{
return fetch(`${url}`,
{
method: "GET",
headers: {
'Authorization': `JWT ${DEMO_TOKEN}`,
}
})
.then(
function(response) {
console.log(response.headers);
console.log(response.status);
console.log(response.url);
if (response.status !== 200) {
console.log('Status Code: ' + response.status);
return;
}
response.json().then((responseData) => {
console.log(responseData);
this.setState({
ver: responseData.results.appversion, // getting error here
});
});
}
)
.catch(function(err) {
console.log('Fetch Error', err);
});
Just to be clear about which this you're trying to reference, could you do this?
async fetchData() {
const ctx = this
And then reference ctx instead of this:
ctx.setState({
ver: responseData.results.appversion,
});

React Native - Sending information so as to receive a response for simple login screen but receiving JSON parse error instead

I have tried several times to send the data and receive a response, but it does not seem to be sending the data put in by the user. I have tried going about this in several ways,I will share the code for the last two.
ONE
state = {
phoneNo: '',
pin: '',
isLoggingIn: false,
message: ''
}
_userLogin = () => {
console.log("userLogin");
this.setState({isLoggingIn: true, message:''});
var params = {
phoneNo: this.state.phoneNo,
pin: this.state.pin
};
var proceed = false;
fetch("https://"+"<url>", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
.then(
(response) => response.json())
.then((response) => {
if (response.status == 200) {
proceed = true;
}
else {
this.setState({ message: response.message });
console.log(message); }
})
.then(() => {
this.setState({ isLoggingIn: false })
if (proceed) this.props.onLoginPress();
})
.catch(err => {
console.log(err.message);
this.setState({ message: err.message });
this.setState({ isLoggingIn: false })
});
}
Two
The only difference here is how I am handling the response so I will only add that section. I thought that the issue might be due to syntax at this point.
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
I have been through various tutorials, github and stackoverflow pages addressing the issue but I seem to be missing something. I keep getting a JSON parse error and I am convinced that perhaps the data is never being sent to the url because I get the error regardless of user input.
Both input fields have a ref and the button points to the user login function.
<TextInput
ref = {component => this._pin = component}
placeholder="pin"
onChangeText = {(pin) => this.setState({pin})}
secureTextEntry = {true}
onSubmitEditing={this._userLogin}
/>
<TouchableOpacity
onPress={this._userLogin}
title = "Submit"
disabled={this.state.isLoggingIn||!this.state.phoneNo||!this.state.pin}>
<Text style={styles.loginText}>Sign In</Text>
</TouchableOpacity>
try something like this.
I also get problem acceding both status code & data from fetch call, so i made "processResponse" function
processResponse=(response) =>{
const statusCode = response.status;
const data = response.json();
return Promise.all([statusCode, data]).then(res => {
return ({
statusCode: res[0], // the status code
data: res[1] // the data of the GET/POST returned by fetch call
})
}
);
}
_userLogin = () => {
console.log("userLogin");
this.setState({isLoggingIn: true, message:''});
var params = {
phoneNo: this.state.phoneNo,
pin: this.state.pin
};
fetch("https://"+"<url>", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
/*processResponse return both status and data , because when you make
.then((response) => response.json()) you return only data and status is removed
*/
.then(this.processResponse)
.then(res => {
console.log("response of fetch",res);
const { statusCode, data } = res;
if (statusCode > 200) {
this.props.onLoginPress()
}else{
this.setState({ message: data.message });
console.log("data message" , data.message);
}
this.setState({ isLoggingIn: false })
})
.catch(err=> {
console.error(err);
this.setState({ message: err.message});
this.setState({isLoggingIn: false})
});
});
}
AlainIb was very helpful and this helped contribute to what worked in the end. Using form data seemed to assist with the JSON Parse error. Hope this helps anyone else who is having any troubles.
state = {
message: ''
}
_processResponse = (response) =>{
const statusCode = response.status;
console.log("resp", response);
const data = response.json();
console.log("data", data);
return Promise.all([statusCode, data]).then(res => {
return ({
statusCode: res[0], // the status code
data: res[1] // the data of the GET/POST returned by fetch call
})
});
}
_userLogin = () => {
console.log("userLogin");
this.setState({isLoggingIn: true, message:''});
var params = {
phoneno: this.state.phoneno,
pin: this.state.pin
};
var formData = new FormData();
formData.append("phoneno", this.state.phoneno);
formData.append("pin", this.state.pin);
console.log(formData);
let data = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type':'multipart/form-data'
},
body: formData
}
console.log(data);
fetch("https://"+"url", data)
.then(this._processResponse)
.then(res => {
console.log("response of fetch",res);
const { statusCode, data } = res;
if (statusCode == 200) {
console.log("in if statement");
if(data.login_success== 1){
console.log("name to be passed", data.name);
console.log("log in to profile");
this.props.navigation.navigate('ProfileRoute');
}else {
console.log("fail");
this.setState({message:"Password or Phone Number is Wrong"});
}
}else{
this.setState({ message: data.message });
console.log("data message" , data.message);
}
this.setState({ isLoggingIn: false })
})
.catch(err=> {
console.error(err);
this.setState({ message: err.message});
this.setState({isLoggingIn: false})
});
}

Categories

Resources