I have an error in react native that says '.then is not a function' in this code where I use .this in .then(()=>{this.manageAccess()})
What can I do?
Or tell me if there is a replacement for .this
export function signIn(data) {
const request = axios({
method:"POST",
url:SIGNIN,
data:{
email: data.email,
password: data.password,
returnSecureToken:true
},
headers:{
"Content-Type":"application/json"
}
}).then( response => {
return response.data
}).catch(e =>{
return false
});
return {
type: SIGN_USER,
payload: request
}
}
class LoginForm extends Component {
manageAccess = () => {
if(!this.props.User.userData.uid){
this.setState({hasErrors:true})
} else {
setTokens(this.props.User.userData,()=>{
this.setState({hasErrors:false});
this.props.navigation.navigate('Dashboard')
})
}
};
submitUserHandler = ()=>{
let isFromValid = true;
let formToSubmit= {};
if(isFromValid){
if(this.state.type === "Login"){
this.props.signIn(formToSubmit).then(()=>{
this.manageAccess()
})
}
}
};
}
Your signIn() function returns an object where the request object is in the payload property
Try changing to
this.props.signIn(formToSubmit).payload.then(...
Related
I have a component which has a form where at the moment to do clic on submit button, I call a function handleSubmit (it is on my component), this function call an action through of dispatch and this action, I make a call to a service (HTTP Request).
handleSubmit
handleSubmit = (e) => {
e.preventDefault()
const { validateFields } = this.props.form;
validateFields((err, params) => {
if (!err) {
const { user, dispatch } = this.props;
let response = dispatch(actions.addDevice(params))
console.log(response); //Response is undefined
}
});
}
actions.addDevice
function addDevice(params){
return (dispatch, getState) => {
let { authentication } = getState();
dispatch(request({}));
service.addDevice(params, authentication.user.access_token)
.then(
response => {
if(response.status === 201) {
dispatch(success(response.data));
}
return response;
},
error => {
dispatch(failure(error.toString()));
dispatch(alertActions.error(error.toString()));
}
)
}
function request(response) { return { type: constants.ADD_DEVICE_REQUEST, response } }
function success(response) { return { type: constants.ADD_DEVICE_SUCCESS, response } }
function failure(error) { return { type: constants.ADD_DEVICE_FAILURE, error } }
}
service.addDevice
function addDevice(params, token){
return axios({
url: 'http://localhost:5000/user/add-device',
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token},
data: {
data1: params.data1,
data2: params.data2,
data3: params.data3
}
})
.then(function(response) {
return response;
})
.catch(function(error) {
return error.response;
});
}
I would like to get the response in my component to be able to make validations but as the request is async, I never can get the response and only prints an undefined variable. How can I get the response sync? Or what do I need do to be able to make validations?
You are not returning the promise service.addDevice.
So you can do return service.addDevice... and in the handleSubmit you do dispatch(...).then((data) => ...do something with the data...)
let response = dispatch(actions.addDevice(params))
this is asynchronous. So it is not surprising to return undefined from console.log(). console.log() execute even before dispatch process is completed. Use promise or async await syntax. I would recommend using the async-await syntax.
handleSubmit = (e) => {
e.preventDefault()
const { validateFields } = this.props.form;
validateFields(async (err, params) => {
if (!err) {
const { user, dispatch } = this.props;
let response =await dispatch(actions.addDevice(params))
console.log(response); //Response is undefined
}
});
}
Please replace your code with this code
handleSubmit
handleSubmit = (e) => {
e.preventDefault()
const { validateFields } = this.props.form;
validateFields((err, params) => {
if (!err) {
const { user, dispatch } = this.props;
dispatch(actions.addDevice(params)).then((response)=>{
console.log(response);
})
}
});
}
actions.addDevice
function addDevice(params){
return (dispatch, getState) => {
let { authentication } = getState();
dispatch(request({}));
return service.addDevice(params, authentication.user.access_token)
.then(
response => {
if(response.status === 201) {
dispatch(success(response.data));
}
return response;
},
error => {
dispatch(failure(error.toString()));
dispatch(alertActions.error(error.toString()));
}
)
}
function request(response) { return { type: constants.ADD_DEVICE_REQUEST, response } }
function success(response) { return { type: constants.ADD_DEVICE_SUCCESS, response } }
function failure(error) { return { type: constants.ADD_DEVICE_FAILURE, error } }
}
import getAuthentication from './getAuthentication';
class Home extends React. Component {
constructor() {
super();
//this.authentication = false;
this.state = {
username: '',
password: '',
check:false,
authentication:false
};
this.err = '';
}
componentDidUpdate() {
console.log (this.state.authentication);
console.log(this.state.authentication == true);
if (this.state.check)
{
const promiseAuthentication = getAuthentication(
this.state.username,
this.state.password,
);
promiseAuthentication
.then(response => {
console.log (response.data.Success);
console.log(response.data.Success == true);
this.setState({check :false, authentication:response.data.Success});
})
.catch(error => {
// console.log(error);
this.err = error;
});
}
if (this.state.authentication == true) {
event.preventDefault();
history.push('/overview');
}
}
assignUsername = event => {
this.setState({ username: event.target.value });
};
assignPassword = event => {
this.setState({ password: event.target.value });
};
handleSubmit = () => {
this.setState({ check:true });
};
==============================================================
getAuthentication.js
import axios from 'axios';
function getAuthentication(username, password) {
const authenticationConfig = {
Email: username,
Password: password,
};
return axios.post(
'http://localhost:5002/login/confirmation',
authenticationConfig,
);
}
export default getAuthentication;
In the above code my this.state.Authentication is not getting updated to true
I am trying to update its value in axios promise.
Can someone please tell me what's wrong? I mean I have tried everything but I am not able to proceed.
How do I change the state of Authentication object and switch new window?
I have a second file that is returning the axios promise where promise value is "undefined".. How do I make async call and resolve this issue ??
componentDidUpdate is wrapped in if (this.state.check). Nothing in the code you pasted sets this.state.check to true. Set this.state.check: true.
I am using redux-thunk . Here, I have one login action. On that action I am calling an API which will give me some token, that I have to store in the state. Then immediately, after success of this action, I have to make another API request which will have this token in the header and will fetch more data. Based on this, I would like to redirect the user.
Login Action
import { generateToken } from '../APIs/login';
import HttpStatus from 'http-status-codes';
import { LOGIN_FAILED, LOGIN_SUCCESS } from '../constants/AppConstants';
import { fetchUserJd } from './GetUserJd';
import history from '../history';
export function fetchToken(bodyjson) {
return (dispatch) => {
getLoginDetails(dispatch, bodyjson);
}
}
export function getLoginDetails(dispatch, bodyjson) {
generateToken(bodyjson)
.then((response) => {
if (response.status === 200)
dispatch(sendToken(response.payload))
else
dispatch(redirectUser(response.status));
})
}
export function sendToken(data) {
return {
type: LOGIN_SUCCESS,
data: data,
}
}
export function redirectUser(data) {
return {
type: LOGIN_FAILED,
data: data,
}
}
2nd Action
import { FETCHING_JOBDESCRIPTION_SUCCESS, FETCHING_DATA_FAILED,FETCHING_JOBS } from '../constants/AppConstants';
import { getUserJobs } from '../APIs/GetUserJd';
import history from '../history';
export function fetchUserJd(token) {
console.log(token);
return (dispatch) => {
dispatch(fetchingJobDescription());
}
};
export function getUserJd(dispatch, token) {
getUserJobs(token)
.then((response) => {
if (response.status === 200)
dispatch(sendUserJd(response.payload))
else
dispatch(fetchFailure(response.status));
})
}
export function fetchFailure(data) {
return {
type: FETCHING_DATA_FAILED,
data: data,
}
}
export function sendUserJd(data) {
return {
type: FETCHING_JOBDESCRIPTION_SUCCESS,
data: data,
}
}
export function fetchingJobDescription() {
return {
type: FETCHING_JOBS
}
}
Calling this from
handleClick(event) {
event.preventDefault();
var bodyJson = {
"username": this.state.UserName,
"password": this.state.password
}
this.props.fetchToken(bodyJson);
}
How can I call that second action immediately after the success of the first request. ?
Tried way ->
componentWillReceiveProps(newProps) {
console.log(newProps.token);
if(newProps.token) {
this.props.fetchUserJd(newProps.token);
}
}
export function sendUserJd(data) {
if (data.data.length > 0) {
history.push('/userJobs');
} else {
history.push('/createJob');
}
return {
type: FETCHING_JOBDESCRIPTION_SUCCESS,
data: data,
}
}
You can do without setting it to redux state. You need to return your success action call to get the token in component itself using promise .then and then call this.props.sendToken(token); which will actually set the data in state and follows your existing flow.
handleClick(event) {
event.preventDefault();
var bodyJson = {
"username": this.state.UserName,
"password": this.state.password
}
this.props.getLoginDetails(bodyJson).then((token) => {
this.props.sendToken(token);
});
}
And in actions
const GET_LOGIN_DETAILS_SUCCESS = 'GET_LOGIN_DETAILS_SUCCESS';
export function getLoginDetailsSuccess(data) {
return {
type: GET_LOGIN_DETAILS_SUCCESS,
data: data,
}
}
export function getLoginDetails(bodyjson) {
generateToken(bodyjson)
.then((response) => {
if (response.status === 200)
return dispatch(getLoginDetailsSuccess(response.payload))
else
dispatch(redirectUser(response.status));
})
}
Let me know if you have any questions or if you feel difficult to understand
I have this code:
signin(context, payload, resolve) {
console.log("SIGNIN action")
const aemail = payload.locmail
const apassw = payload.locpass
backend.get("api/auth/signin", {
headers: {
'planck': 'FRESH'
},
crossDomain: true,
params: {
password: apassw,
email: aemail
}
}).then(function(ret) {
console.log("SENT")
if (ret.data.auth === 'TRUE') {
context.commit('authenticate', ret.data.planck)
state.isAuthenticated = true
} else {
state.isAuthenticated = false
}
console.log(ret)
return Promise.resolve(ret)
});
}
and when I call it from component:
this.$store.dispatch('signin', {
locmail,
locpass
}).then(ret => {
console.log(ret);
});
then console log prints undefined. What am I doing wrong here? In documentation I read that I should use resolve() but then I get error that it's not a function.
Return the backend promise in the signin action.
signin(context, payload) {
// ...
// The action needs to return a Promise
return backend.get("api/auth/signin", {
/* ...*/
}).then(function(ret) {
/* ... */
});
}
Also, it looks like you're changing a state object in the action and this should be limited to mutations.
If you're using the strict mode in development, you'll see a warning about this.
You are not returning the promise. Change your signin() function to this as #Emile Bergeron suggested:
signin(context, payload) {
console.log("SIGNIN action")
const aemail = payload.locmail
const apassw = payload.locpass
return backend.get("api/auth/signin", {
headers: {
'planck': 'FRESH'
},
crossDomain: true,
params: {
password: apassw,
email: aemail
}
}).then(function(ret) {
console.log("SENT")
if (ret.data.auth === 'TRUE') {
context.commit('authenticate', ret.data.planck)
state.isAuthenticated = true
} else {
state.isAuthenticated = false
}
console.log(ret)
return Promise.resolve(ret)
});
}
I am trying to chain dispatches with redux-thunk. I have 2 action creator as below:
getResourceLinks:
export const getResourceLinks = () => {
return dispatch => {
let req = {
url: getRootUrl(),
header: {
Accept: 'application/json'
}
};
return request(req).then(res => {
dispatch({
type: ActionTypes.RESOURCE.LOAD_URL_SUCCESS,
payload: res.body
});
}).catch(err => {
dispatch({
type: ActionTypes.RESOURCE.LOAD_URL_ERROR,
payload: err
});
});
}
};
and loadAppliances:
export const loadAppliances = () => {
return (dispatch, getState) => {
return dispatch(getResourceLinks()).then(res => {
const {resources} = getState();
let req = {
url: getResourceLink(Resources.Appliances, res.body),
header: {
Accept: 'application/json'
}
};
request(req).then(res1 => {
dispatch({
type: ActionTypes.APPLIANCE.LOAD_SUCCESS,
payload: res1.body
});
}).catch(err => {
dispatch({
type: ActionTypes.APPLIANCE.LOAD_ERROR,
payload: err
});
});
});
};
};
I am facing with an error: Uncaught TypeError: Cannot read property 'then' of undefined at line 3 in loadAppliances action. Promise was returned correctly, wasn't it? Am I doing wrong something? I've seen carefully examples of thunk-redux but I don't still find out what was wrong.
Update. Here is request:
import superagent from 'superagent';
import superagentPromisePlugin from 'superagent-promise-plugin';
import {RequestMethods} from '../constant';
const request = ({url, method = RequestMethods.GET, param, body, header}) => {
let methodStr;
switch (method) {
case RequestMethods.POST:
methodStr = 'POST';
break;
case RequestMethods.PUT:
methodStr = 'PUT';
break;
case RequestMethods.DELETE:
methodStr = 'DELETE';
break;
default:
methodStr = 'GET';
break;
}
let req = superagent(methodStr, url).use(superagentPromisePlugin);
//set header
if (header) {
req.set(header)
}
//set param
if (param) {
req.query(param)
}
//set body
if (body) {
req.send(body)
}
return req;
};
export default request;
The problem here is that dispatch does not return your promise. It actually returns the dispatched action itself. (reference).
return dispatch(getResourceLinks()).then(res => {
^--- this is the problem
The way I would approach this is to dispatch an action after your first successful call and store any pertinent information in the state, then dispatch the next call and store its response.
Example
const getResourceLinks = () => {
return request({
url: getRootUrl(),
header: {
Accept: 'application/json'
}
});
};
const getAppliances = (appliances) => {
return request({
url: getResourceLink(Resources.Appliances, appliances),
header: {
Accept: 'application/json'
}
})
};
export const loadAppliances = () => {
return (dispatch, getState) => {
getResourceLinks()
.then(res => {
dispatch({
type: ActionTypes.RESOURCE.LOAD_URL_SUCCESS,
payload: res.body
});
return getAppliances(res.body)
.then(res1 => {
dispatch({
type: ActionTypes.APPLIANCE.LOAD_SUCCESS,
payload: res1.body
});
})
.catch(err => {
dispatch({
type: ActionTypes.APPLIANCE.LOAD_ERROR,
payload: err
});
});
})
.catch(err => {
dispatch({
type: ActionTypes.RESOURCE.LOAD_URL_ERROR,
payload: err
});
});
}
}
You also might want to take a look at redux-saga