0

I'm having an issue with calling useEffect from this function. I haven't been using React that long so I may have some glaring issues but this is taking up too much time.

My function is as follows:

import React, { Component } from 'react';
import { useState, useEffect } from "react";

export function Sessions() {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [count, setCount] = useState(null);

    useEffect(() => {
        fetch(`https://localhost:7126/api/`)
            .then((response) => {
                if (!response.ok) {
                    throw new Error(
                        `This is an HTTP error: The status is ${response.status}`
                    );
                }
                return response.json();
            })
            .then((actualData) => {
                setData(actualData);
                setError(null);
                setCount(actualData.length);
            })
            .catch((err) => {
                console.log(err.message);
            });
    }, []);


    return (
        <div className="App">
            <h1>Stream Request: {count} records</h1>
            {loading && <div>A moment please...</div>}
            {error && (
                <div>{`There is a problem fetching the post data - ${error}`}</div>
            )}
            <ul>
                {data &&
                    data.map(({ StreamId, EntryTime }) => (
                        <li key={StreamId}>
                            <h3>{EntryTime}</h3>
                        </li>
                    ))}
            </ul>
        </div>
    );
}

The error i'm receiving is

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app

#1)I have updated React and React-Dom they were both up to date.
#2) ? I don't think I am?

#3) I have verified this using npm ls react and my output is as follows:

+-- [email protected]
| `-- [email protected] deduped
+-- [email protected]
| +-- [email protected]
| | `-- [email protected] deduped
| `-- [email protected] deduped
+-- [email protected]
`-- [email protected]
  +-- [email protected]
  | `-- [email protected] deduped
  +-- [email protected]
  | `-- [email protected] deduped
  `-- [email protected] deduped

All seem to be deduped? Please help, none of the other questions have helped my issue such as :Invalid Hook Call but not really

Edit I use Sessions via App.js & AppRoutes.js App.js:

import "./stylesheet.css";
import React, { Component } from 'react';
import { Route, Routes } from 'react-router-dom';
import AppRoutes from './AppRoutes';
import { Layout } from './components/Layout';


export default class App extends Component {
    static displayName = App.name;

    render() {
        return (
            <Layout>
                <Routes>
                    {AppRoutes.map((route, index) => {
                        const { element, ...rest } = route;
                        return <Route key={index} {...rest} element={element} />;
                    })}
                </Routes>
            </Layout>
        );
    }
}

AppRoutes.js:

import { Sessions } from "./components/Sessions";
import { Messages } from "./components/Messages";
import { Home } from "./components/Home";

const AppRoutes = [
  {
    index: true,
    element: <Home />
  },
  {
    path: '/sessions',
    element: <Sessions />
  },
  {
    path: '/messages',
    element: <Messages />
  }
];

export default AppRoutes;
4
  • 2
    Please show how do you use Sessions Commented Nov 15, 2022 at 19:00
  • @KonradLinkowski I edited above to show, not sure if Sessions should remain a function or a class..? thank u Commented Nov 15, 2022 at 19:06
  • 1
    The minimal code seems to be working in a codesandbox, codesandbox.io/s/suspicious-rhodes-kjpnck?file=/src/App.tsx Commented Nov 15, 2022 at 19:25
  • Should i switch this to a class with a constructor{}? I'm still confused why this doesn't work... Commented Nov 16, 2022 at 16:12

1 Answer 1

1

I know this is probably not the solution but maybe it could give you some ideas. As you are not awaiting the call properly inside your useEffect(), it could be causing issues for your code and errors that are not that descriptive.

Here are some suggestions:

  • use the async/await API instead of the .then()/.catch() from Promises.
  • create an internal function for your asynchronous function and call it inside the useEffect() hook after defining it. In general (from my experience), async calls at "top-level" useEffect() hook trigger some warnings.

As a possible solution, this is the code I suggest you change and start from:

useEffect(() => {
  const internalFetch = async () => {
    try {
      const actualData = await fetch(`https://localhost:7126/api/`)
      setData(actualData);
      setError(null);
    } catch (err) {
      console.log(err.message);
    }
  }

  internalFetch();
}, []);

You could use data.length directly instead of creating a state for count.

Again: I don't know if this will fix your issue but it could give you another error that could be more descriptive. And, also as a final suggestion, you could use a lib for fetching data such as react-query, that isolates and cache your data for you.

Sign up to request clarification or add additional context in comments.

2 Comments

This gives me an 'unexpected token' error on the last line of }, []);
You probably didn't closed the } or closed more }s than necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.