I am using reactJS.
I have a child component which looks like:
const Child = ({callback}) => {
const handleSubmit = async e => {
console.log(await callback()); //callback returns an async value
}
return (
<div> some stuff here </div>
)
}
export default Child;
I use my Child component on parent component like :
const Parent = () => {
const sendSomeDataToServer = () => {
axios({
//some stuff here...
})
.then((res) => return {serverInfo: 'OK'})
.catch((err) => {
if(err.response.status < 500)
return {serverInfo: 'e.response.data'}
else
return {serverInfo: 'Unexpected error'}
}
}
return (
<Child callback={sendSomeDataToServer} />
)
}
export default Parent;
but I don't know why the returned value by sendSomeDataToServer
is always undefined...
Looks like await not working as expected, any idea how to fix that ?
CodePudding user response:
You forget to add a return statement before Axios
you are not returning anything from sendSomeDataToServer function.
const Parent = () => {
const sendSomeDataToServer = () => {
return axios({
//some stuff here...
})
.then((res) => ({serverInfo: 'OK'}))
.catch((err) => {
if(err.response.status < 500)
return {serverInfo: 'e.response.data'}
else
return {serverInfo: 'Unexpected error'}
}
}
return (
<Child callback={sendSomeDataToServer} />
)
}
CodePudding user response:
const handleSubmit = aync e
not aync, it is async