As i just know basic of axios and not able to convert this fetch to axios method. I have the following piece of code which is working perfect i am confused do i need to use Json.stringify or any other json method as what i have read is axios do automatically converts to json
here is my code
const handleFormSubmit = event => {
event.preventDefault();
setData({
...data,
isSubmitting: true,
errorMessage: null
});
fetch("https://hookedbe.herokuapp.com/api/login", {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: data.email,
password: data.password
})
})
.then(res => {
if (res.ok) {
return res.json();
}
throw res;
})
.then(resJson => {
dispatch({
type: "LOGIN",
payload: resJson
})
})
.catch(error => {
setData({
...data,
isSubmitting: false,
errorMessage: error.message || error.statusText
});
});
};
changing it to axios
const url = "https://hookedbe.herokuapp.com/api/login"
const body = {
username: data.email,
password: data.password
};
axios.post(url, body)
.then(res => {
dispatch({
type: "LOGIN",
payload: res.data
})
})
.catch(error => {
console.log(error);
})
You can use axios.post, much easier syntax and no need for any json conversion:
const payload = {
username: data.email,
password: data.password
};
axios.post("https://hookedbe.herokuapp.com/api/login", payload)
.then(res => {
dispatch({
type: "LOGIN",
payload: res.data
})
})
.catch(error => {
console.log(error);
})
Related
I have a form built in react js and I am using an axios post request to register a user after form submission. I have tried to put a try catch block after the promise but i dont think i am getting passed the post request. I have imported axios and checked package json to make sure its downloaded. I have also implemented a catch block to catch errors but I am still getting
(TypeError: Cannot read properties of undefined (reading 'post'))
const handleSubmit = (e) => {
e.preventDefault();
axios.post('http://localhost:5000/api/users/register',{
name: data.name,
email:data.email,
password: data.password
})
.then((res) => {
console.log("server response:",res);
})
.catch((err) =>{
console.log("Server responded with error", err);
})
}
It is indeed correct to use axios.post in that way but you are not handling a response or an error from the server. For these axios provides you with the .then() and .catch() methods, which handle the results/error for you.
Here's an example:
(You can check the results of the post request in this example in the console tab or the network tab in the developer tools of your favorite browser).
const RegisterScreen = () => {
const [ data, setData ] = useState({
name: "",
email: "",
password: "",
});
const handleChange(e) => {
setData({...data, [e.target.name]: e.target.value});
}
const handleSubmit = (e) => {
e.preventDefault();
axios.post("YOUR/URL:5000", {
name: data.name,
email: data.email,
password: data.password
})
.then((res) => {
console.log("Server response: ", res);
})
.catch((err) => {
console.log("Server respondend with error: ", err);
})
}
}
return (
<>
<YourForm />
</>
);
}
You may have to specify the content type while sending a POST request.
const handleSubmit = (e) => {
e.preventDefault();
axios.post('http://localhost:5000/api/users/register',{
name: data.name,
email:data.email,
password: data.password
}, {
headers: {
'Content-Type': 'application/json' }
})
.then((res) => {
console.log("server response:",res);
})
.catch((err) =>{
console.log("Server responded with error", err);
})
}
I have a block of code in ReactJS with FETCH api that is working perfectly fine but when I tried to replace it with AXIOS then its not functioning perfectly, even though I checked the documentation.
WORKING CODE OF FETCH API:
const signup = (user) => {
return fetch(`${API}/signup`, {
method: "POST",
headers: {
Accept: 'application/json',
"Content-Type": 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => {
console.log(err);
});
}
const clickSubmit = (event) =>{
event.preventDefault();
signup({name, email, password})
.then(data => {
if(data.error){
setValues({...values, error: data.error, success: false})
}
else{
setValues({...values, name: '', email: '', password: '', error:'', success:true})
}
})
}
NOT WORKING SAME CODE BUT WITH AXIOS LIBRARY:
import axios from 'axios';
const signup = (user) => {
return axios(`${API}/signup`, {
method: "POST",
headers: {
Accept: 'application/json',
"Content-Type": 'application/json'
},
data: JSON.stringify(user)
})
.then(response => {
return response.data;
})
.catch(err => {
console.log(err);
});
}
const clickSubmit = (event) =>{
event.preventDefault();
signup({name, email, password})
.then(data => {
if(data.error){
setValues({...values, error: data.error, success: false})
}
else{
setValues({...values, name: '', email: '', password: '', error:'', success:true})
}
})
}
The error that is coming after writing the above code with axios library is:
Unhandled Rejection (TypeError): Cannot read property 'error' of undefined
What is wrong in the code with axios ?
Note:
Apparently I narrowed it down to the place where undefined is coming.
signup({name, email, password})
.then(data => {
if(data.error){
setValues({...values, error: data.error, success: false})
}
else{
setValues({...values, name: '', email: '', password: '', error:'', success:true})
}
})
}
Here in the .then() block 'data' is coming as undefined and I don't know why as with fetch api its working fine.
Reference the documentation of Axios found here: https://github.com/axios/axios#response-schema
What you are missing is
.then(response => {
return response.data;
})
instead of:
.then(response => {
return response;
})
I am making an app where I send and receive data from one API. Once I get this data I want to make another call to the some other API sending this data to this second API and receiving data from this second API.
export const uploadImage = (data) => (dispatch) => {
dispatch({ type: UPLOAD_IMAGE });
axios({
method: 'post',
url: 'http://3.14.136.182:80/predict',
data: data,
"mimeType": "multipart/form-data",
headers: {
'content-type': 'multipart/form-data'
},
timeout: 20000
})
.then((response) => {
dispatch({ type: UPLOAD_IMAGE_SUCCESS, payload: response.data });
data = response.data;
axios({
method: 'post',
url: '3.14.136.182:8005/finalResult',
data: data,
"mimeType": "multipart/form-data",
headers: {
'content-type': 'multipart/form-data'
},
timeout: 20000
})
.then((response) => {
dispatch({ type: UPLOAD_IMAGE_SUCCESS, payload: response.data});
console.log("Mehmood",response.data);
})
.catch((error) => {
dispatch({ type: UPLOAD_IMAGE_FAILURE });
})
})
.catch((error) => {
dispatch({ type: UPLOAD_IMAGE_FAILURE });
})
}
You are missing at one return statement in you first then block. (before axios). Also you are dispatching success two times.
I'm trying to update my actions to axios from fetch.
For example my current login looks like this:
export const login = (email, password) => {
return (dispatch) => {
dispatch({
type: 'CLEAR_MESSAGES'
});
return fetch('/login', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: email,
password: password
})
}).then((response) => {
if (response.ok) {
return response.json().then((json) => {
dispatch({
type: 'LOGIN_SUCCESS',
token: json.token,
user: json.user
});
cookie.save('token', json.token, { expires: moment().add(1, 'hour').toDate() });
browserHistory.push('/account');
});
} else {
return response.json().then((json) => {
dispatch({
type: 'LOGIN_FAILURE',
messages: Array.isArray(json) ? json : [json]
});
});
}
});
};
}
So far for the conversion to axios, I have this:
export const login = (email, password) => {
// const { email, password } = this.props;
(dispatch) => {
dispatch({
type: 'CLEAR_MESSAGES'
})
axios({
method: 'post',
url: '/login',
data: { email: email, password: password }
}).then((response) => {
dispatch({
type: 'LOGIN_SUCCESS',
token: json.token,
user: json.user
});
cookie.save('token', json.token, { expires: moment().add(1, 'hour').toDate() });
browserHistory.push('/account');
})
.catch(() => dispatch({
type: 'LOGIN_FAILURE',
messages: Array.isArray(json) ? json : [json]
})
)
}}
Its not working :( and I'm not sure what I'm doing wrong - not too familiar with axios.
I'm getting this error in Google Chrome console
I believe the error is cause you're calling a json variable that is not present in your updated code.
You need to access the data via response.data. When using fetch() it made sense to convert the response with response.json() and use a thenable to tap into that json, but with axios, you can reach into the response right away without any conversions.
export const login = (email, password) => {
return (dispatch) => {
dispatch({
type: 'CLEAR_MESSAGES'
})
axios.post("/login", {email, password}).then((response) => {
dispatch({
type: 'LOGIN_SUCCESS',
token: response.data.token,
user: response.data.user
});
cookie.save('token', json.token, { expires: moment().add(1, 'hour').toDate() });
browserHistory.push('/account');
})
.catch(() => dispatch({
type: 'LOGIN_FAILURE',
messages: Array.isArray(json) ? json : [json]
})
)
In my React component this.login() isn't executing. I believe this is because an await function changes the context of this, but I'm not sure how to fix it.
await this.props
.SignupUser({
variables: {
email: this.state.email,
password: this.state.password,
name: this.state.name,
},
})
.then(() => {
this.login();
})
.catch(error => {
this.setState({ wait: false });
const errorMessage = error.graphQLErrors[0].functionError;
this.setState({ error: errorMessage });
});
Remove await keyword, It should work.
Alternatively, we need to implement in a different way
The function must add async keyword in the function declaration for below code
await this.props
.SignupUser({
variables: {
email: this.state.email,
password: this.state.password,
name: this.state.name,
},
})
.then(() => {
this.login();
})
.catch(error => {
this.setState({ wait: false });
const errorMessage = error.graphQLErrors[0].functionError;
this.setState({ error: errorMessage });
});
(or)
try {
const user = await this.props
.SignupUser({
variables: {
email: this.state.email,
password: this.state.password,
name: this.state.name,
},
});
this.login();
} catch (e) {
this.setState({ wait: false });
const errorMessage = error.graphQLErrors[0].functionError;
this.setState({ error: errorMessage });
}