Error: Attempting to use hooks outside the scope of a function component in react-native. Hooks can only be called within the body of a

Oops! An error occurred: Invalid hook call. Hooks can only be called inside the body of a function component. There are several reasons why this might have happened:

  1. You could have incompatible versions of React and the renderer (e.g., React DOM)
  2. Your code might not be following the Rules of Hooks
  3. There could be multiple copies of React in the same application

I'm currently working on implementing location permission in a React Native project using expo CLI.

Below is the function I've created:

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);
  // FETCHING DATA
  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éessayer ultérieurement!"
        );
        setLoading(false);
      });

      // GEOLOCATION TEST
      // STATE FOR GEOLOCATION
  const [location, setLocation] = useState<any | null>(null);
  const [hasPermission, setHasPermission] = useState<any | null>(null);
    useEffect(() => {
      (async () => {
          const { status } = await Location.requestForegroundPermissionsAsync();
          setHasPermission(status === "granted");
          let location = await Location.getCurrentPositionAsync({});
      })();
  }, []);
}
export default OfferScreen;

Here's the target function in my tab bar as well:

<Tab.Screen // TAB SCREEN OFFER
                options={
                    { headerShown: false }
                }
                name={"Offres"}
                component={Offers}/>

By the way, everything works fine when I remove the location permission code.

Answer №1

A common mistake is placing useState() inside of a React.useEffect(). To fix this, move these statements to the top and outside of the useEffect block.

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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the code require the use of window when the Javascript error object is not functioning properly?

I'm struggling to grasp the distinction between var maxResult = window.max(maxValInt1, maxValInt2); which functions properly, and var maxResult = max(maxValInt1, maxValInt2); which gives an error "object is not a function". Why do I have to inclu ...

How can I integrate custom PHP pages into Odoo Community 12?

I am looking for a way to integrate my custom PHP webpages with the login page of Odoo Community that is already set up and functioning on my server. I want specific users to be redirected to my custom pages after logging in. Any suggestions on how to ac ...

What are the best ways to incorporate a theme into your ReactJS project?

Looking to create a context for applying dark or light themes in repositories without the need for any manual theme change buttons. The goal is to simply set the theme and leave it as is. Currently, I have a context setup like this: import { createContext ...

How can you use Knex to order the results for each WHERE clause in a SELECT query?

When querying a database using knex, the desired results should be ordered in a specific manner. The current code provides the required results but lacks the expected order. knex("FRUITTBL") .select("FruitTag", "FruitName", ...

Troubleshooting: Why is my console.log not working in JavaScript

Recently, I've been diving into the world of JavaScript, but for some reason, I can't seem to make console.log function properly. At the top of my HTML document in the head section, I added jQuery like this: <script type="text/javascript" sr ...

Unlocking the Power of NVM: A Guide to Using Different NPM Versions

After relying on NPM for several years, I decided to give NVM a try. The need arose for me to have two different versions installed, so I removed NodeJS and opted for NVM instead. Upon checking with nvm list, I noticed that there were a total of three ver ...

The initial render of Keen-slider in NextJS can sometimes encounter difficulties when using server-side rendering

While incorporating the keen-slider library v5.4.0 into my nextJS project with TypeScript, I encountered a peculiar issue. The error arises when the keen-slider is initially loaded for the first time, resulting in mismatched transform types causing items ...

What is the best way to set the `value` attribute and `v-model` attribute for a custom Vue component?

I am seeking to develop a unique Vue component that functions as a "radio div" - essentially, a div with the ability to act like a radio button where only one among multiple can be selected at a time. The div will also have a slot for including any desired ...

Utilizing React Router to dynamically render components based on JSON object data

My current challenge involves rendering React components based on the component names in a JSON file I've created. Specifically, I want to render the TestSection component within the context of my Route component. To achieve this, I am utilizing the ...

What is the process by which npm consolidates the dependencies when multiple versions of the same dependency are needed?

To provide a clearer explanation of my query, I have put together a simplified version of a dependency tree: A --> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="044644352a342a34">[email protected]</a> --> ...

Using Javascript to replace elements with input fields and text areas

I'm currently working on a unique project for my Wordpress blog, where I am developing a custom block editor using JavaScript on the frontend. The goal is to convert all elements from the post content into a series of inputs and textareas. To begin, ...

Terminating a Kubernetes container running a React app during the build process with a KILL -9

Looking for guidance on deploying a React app to Kubernetes using a Dockerfile and hosting it with Nginx. Here's what my Dockerfile currently looks like: FROM node:14-alpine as build # Install git RUN apk update && apk upgrade && &bso ...

JavaScript recording speed

I am currently working on a project that involves video recording on my website. After creating a canvas and pushing the recorded frames to it, I have encountered an issue. The playback of the video is too fast - a 10-second video plays in around 2 second ...

Following the submission of a POST request, an error occurred stating: "Unable to assign headers once they have been sent to

I'm having trouble figuring out what's wrong with my code. Whenever I send a post request, I get an error message saying "Cannot set headers after they are sent to the client". My model includes a comment schema with fields for user, content, and ...

Despite a successful request, the React Redux action was not dispatched

I'm currently working on adding authentication to my project. While the user registration part seems to be working, the actions are not being dispatched. Strangely, a similar action for fetching data is working fine and dispatching the actions. Here&a ...

Merging files in npm with glob patterns (without Grunt or Gulp)

I have been exploring the concept of utilizing npm as a build tool. My goal is to achieve something straightforward, like concatenating all CSS files together. However, I have not come across an npm module that specifically does this. There is a package c ...

Choosing a particular svg path in d3.js using JSON attribute

Is it feasible to isolate just one of the SVG paths generated from a geoJSON file using D3? In my scenario, the paths represent different areas on a map. Users can pick an area from a dropdown menu. I aim to utilize the selected value from this list to pin ...

Can the load API in jQuery be utilized to load fragments using a class selector instead of an id?

I've been working on enhancing a website's dashboard by incorporating more widgets onto the page. Interestingly, these widgets are already present on another page within the same domain. After some research, I discovered that utilizing the load A ...

Error: The data from the intermediate value cannot be parsed using the parseFromString() method and replaced with another value,

I'm working on a project where I need to display parsed HTML content within an element. However, before displaying it, I need to make some changes to the HTML using the `replace` method. But unfortunately, I encountered a TypeError: (intermediate valu ...

When I request the value of a JavaScript object, I am met with 'undefined'

I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below: function shop_info(name, latitude, l ...