I want to pass the result from an api call made on the child component to parent component so:
PARENT:
const Parent = () => {
function logFunction(resultFromAPI) {
console.log(resultFromAPI);
}
return(
<Child result={ logFunction } />
)
}
export default Parent
CHILD COMPONENT
const Child = ({result}) => {
const [values, setValues] = useState({
name: ''
})
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
const response = await createApi(values);
if (response.data.message) {
setValues({
name: "",
});
result(response.data); //Uncaught (in promise) TypeError: result is not a function
}
if (response.data.error) {
toast("error", response.data.message);
}
};
return(
<form onSubmit={handleSubmit}>
<Input
name='name'
value={name}
onChange={handleChange("name")}
/>
</form>
<button type='submit'>Submit</button>
)
}
export default Child
The form sends the "name" value on clic of the button to the function "handleSubmit" the function call an API.
The then, i want to call the "result" function from the child props. Put the result from the api on the function and log it on the parent.
But I got the error:
Uncaught (in promise) TypeError: result is not a function
CodePudding user response:
The error message suggests that the "result" prop passed from the parent component to the child component is not a function.
Here are a few things you can try:
Verify the type of the "result" prop passed to the child component: console.log(typeof result);
Make sure that the "logFunction" function is passed as a prop to the child component: return ( <Child result={logFunction} /> );
Make sure that you are calling the "result" function correctly:
result(response.data);
If you still encounter the error after trying these steps, please check the rest of your code and make sure that there are no other issues.
CodePudding user response:
You will need to do binding when passing functions. In you case may be change the logFunction to
logFunction = () => {
console.log(resultFromAPI);
}