React Hooks Error: Hooks Can Only Be Called Inside the Body of a Function Component

Invalid hook call. Hooks can only be called inside of the body of a function component

You can only call hooks from React functions. Read more here.

Just convert the Allowance class component to a functional component.

Working CodeSandbox demo.

const Allowance = () => {
const [allowances, setAllowances] = useState([]);

useEffect(() => {
fetch("http://127.0.0.1:8000/allowances")
.then(data => {
return data.json();
})
.then(data => {
setAllowances(data);
})
.catch(err => {
console.log(123123);
});
}, []);

const classes = useStyles();
return ( <
Paper className = {
classes.root
} >
<
Table className = {
classes.table
} >
<
TableHead >
<
TableRow >
<
TableCell > Allow ID < /TableCell> <
TableCell align = "right" > Description < /TableCell> <
TableCell align = "right" > Allow Amount < /TableCell> <
TableCell align = "right" > AllowType < /TableCell> <
/TableRow> <
/TableHead> <
TableBody > {
allowances.map(row => ( <
TableRow key = {
row.id
} >
<
TableCell component = "th"
scope = "row" > {
row.AllowID
} <
/TableCell> <
TableCell align = "right" > {
row.AllowDesc
} < /TableCell> <
TableCell align = "right" > {
row.AllowAmt
} < /TableCell> <
TableCell align = "right" > {
row.AllowType
} < /TableCell> <
/TableRow>
))
} <
/TableBody> <
/Table> <
/Paper>
);
};

export default Allowance;

Invalid hook call. Hooks can only be called inside of the body of a function component (react-native)

You can't have useState() inside of an React.useEffect().
Move these statements to the top and outside of the useEffect

function OfferScreen({ navigation }: { navigation: any }) {
//STATE VARIABLES FOR FETCHING DATA
const [loading, setLoading] = useState(true);
const [data, setData] = useState([]);
const value = new Animated.Value(1);

//GEOLOCATION TEST
//STATE FOR GEOLOCATION
const [location, setLocation] = (useState < any) | (null > null);
const [hasPermission, setHasPermission] = (useState < any) | (null > null);

React.useEffect(() => {
if (!loading && data) {
(async () => {
const { status } = await Location.requestForegroundPermissionsAsync();
setHasPermission(status === "granted");
let location = await Location.getCurrentPositionAsync({});
})();
}
}, [data, loading]);

//FETCHING DATA
React.useEffect(() => {
fetch("https://fidness.net/WSExchange/getListActiveProspectus")
.then((response) => response.json())
.then((json) => {
setData(json);
setLoading(false);
})
.catch((error) => {
alert(
"Erreur avec le chargement des offres, veuillez réssayer ultérieurement!"
);
setLoading(false);
});
}, []);
}

export default OfferScreen;

ncaught Error: Invalid hook call. Hooks can only be called inside of the body

Sir. I think you made a typo and the error is due to that.
Change useNavigate to useNavigate()

import React, { useEffect, useState } from 'react'
import { Button, Container, Form } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { login } from '../actions/userAction'
import ErrorMessageBox from '../components/ErrorMessagebox'
import Loading from '../components/Loading'

export const SignInScreen = () => {
const navigate = useNavigate()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')

const { search } = useLocation()
const redirectInUrl = new URLSearchParams(search).get('redirect')
const redirect = redirectInUrl ? redirectInUrl : '/'

const userLogin = useSelector((state) => state.userLogin)
const { userInfo, loading, error } = userLogin
const dispatch = useDispatch()

useEffect(() => {
if (userInfo) {
navigate(redirect)
}
}, [navigate, userInfo, redirect])

const submitHandler = (e) => {
e.preventDefault()
dispatch(login(email, password))
}

return (
<Container className="small-container">
<h1 className="my-3">Sign In</h1>
{error && <ErrorMessageBox variant="danger">{error}</ErrorMessageBox>}
{loading && <Loading />}
<Form onSubmit={submitHandler}>
<Form.Group className="mb-3" controlId="email">
<Form.Label>Email</Form.Label>
<Form.Control
type="email"
required
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
required
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<div className="mb-3">
<Button type="submit">Sign In</Button>
</div>
<div className="mb-3">
New Customer?{' '}
<Link to={`/signup?redirect=${redirect}`}>Create new account</Link>
</div>
</Form>
</Container>
)
}

Hooks can only be called inside of the body of a function component. Error: Invalid hook call

You can use hooks only inside of function components. Therefore you can't use useContext(CartContext) just like that outside of any function component.

I assume that you want to use the context inside of ProductCard? Then you have to either rewrite it to a function component:

function ProductCard (props){
const {addItemToCart} = useContext(CartContext)


return ...

}

or wire your class component to the context.

Read more about both ways here

UseState - Invalid hook call. Hooks can only be called inside the body of a function component

The react-search-box you're using uses React 17. This is not compatible with React 18. As a result, once your data state is populated and the <ReactSearchBox is invoked, an error is thrown.

Your code itself is fine - it's the dependency that's the problem.

Either:

  • fork react-search-box and upgrade it to make it compatible with React 18, and use that version instead
  • downgrade your React version to React 17
  • come up with your own search box to remove the dependency on react-search-box
  • wait for react-search-box's maintainers to update to React 18

React Redux-Toolkit: Invalid hook call - Hooks can only be called inside of the body of a function component

Your error is caused by this

Navigate({ to: "/" });

This is the incorrect way to use Navigate. I think based on your code you want to use the hook useNavigate() instead

Also your redux is incorrect (not causing your error but...)

const user = useSelector((state) => state.loggedInUser); 

user would always be undefined because in your reducer you don't have a state called loggedInUser you only have user that points to your userReducer.

This should give you what you want:

const user = useSelector((state) => state.user.loggedInUser);


Related Topics



Leave a reply



Submit