Reputation: 23
This is my Main.js file
import React from 'react';
import axios from 'axios';
const editByID = (id) =>{
axios.post('http://localhost:8000/getbyID',{
id:id
})
.then(({data}) => {
if(data.success == 1){
alert(data.msg);
let tmpArr = [];
for( var i = 0 ; i < data.user.length ; i++ ){
tmpArr.push(data.user[i])
}
// uid = data.user[0].id;
return tmpArr
// console.log(data.user[0].id);
// editUser(uid);
}
else{
alert(data.msg);
}
})
.catch(error => {
console.log(error);
});
} //editByID
export default HomePage;
export {getData,editByID};
This is my FormUpdate.js file
componentDidMount(){
this.getAllByID();
}
getAllByID = () =>{
editByID().then(tmpArr=>{
this.setState({
items:tmpArr
},
()=>{
console.log(this.state);
})
})
} //getAllByID
in FormUpdate.js tmpArr is not getting as an array. But why? It show the following error:
TypeError: Cannot read property 'then' of undefined
FormUpdate.getAllByID
F:/react/react-crud/src/components/FormUpdate.js:21
18 |
19 | getAllByID = () =>{
20 | console.log(this.props.location.id);
> 21 | editByID(this.props.location.id).then(tmpArr=>{
| ^ 22 |
23 | this.setState({
24 | items:tmpArr
What I'm doing wrong? when I'm doing console.log(tmpArr) from Main.js it shows result perfectly.
Upvotes: 0
Views: 345
Reputation: 81
Similar to Rashomon's suggestion, you could just use an Object Literal Syntax by wrapping it in parentheses instead of curly brackets.
const editByID = (id) => (
axios.post('http://localhost:8000/getbyID',{
id:id
})
.then(({data}) => {
if(data.success == 1){
alert(data.msg);
let tmpArr = [];
for( var i = 0 ; i < data.user.length ; i++ ){
tmpArr.push(data.user[i])
}
// uid = data.user[0].id;
return tmpArr
// console.log(data.user[0].id);
// editUser(uid);
}
else{
alert(data.msg);
}
})
.catch(error => {
console.log(error);
})
);
Upvotes: 0
Reputation: 9652
You aren't returning a promise in your editById. Try this
const editByID = (id) =>{
return axios.post('http://localhost:8000/getbyID',{
id:id
})
.then(({data}) => {
if(data.success == 1){
alert(data.msg);
let tmpArr = [];
for( var i = 0 ; i < data.user.length ; i++ ){
tmpArr.push(data.user[i])
}
// uid = data.user[0].id;
return tmpArr
// console.log(data.user[0].id);
// editUser(uid);
}
else{
alert(data.msg);
}
})
.catch(error => {
console.log(error);
});
}
Upvotes: 0
Reputation: 6762
editById
doesnt return anything. Add the return
keyword:
const editByID = (id) => {
return axios.post('http://localhost:8000/getbyID',{ // Add return here
id:id
})
...(rest of code)...
Upvotes: 1