0

I am working with pern stack and when I try using useEffect or useState, I am getting this error. so, I used postgres to create database and used express to connect using pool

created a endpoint and tried fetching that in my code

import React, {useEffect , useState} from 'react';
import Table  from './Table';
import Nav from './Navi';
import TemplateList from './TemplateList';
import {Tab,Tabs} from 'react-bootstrap';
class Dashboard extends React.Component{
  const [tdata,setTdata] = React.useState([]);

  info = async () => {
    try {
      const response = await fetch("http://localhost:8080/dashboard");
      const dataServer = await response.json();
      React.setTdata(dataServer);
    } catch (err) {
      console.error(err.message);
    }
  }
  console.log(tdata);

  React.useEffect(() => {
    info();
  }, []);

error

Failed to compile
./src/components/Dashboard.js
  Line 7:9:  Parsing error: Unexpected token

   5 | import {Tab,Tabs} from 'react-bootstrap';
   6 | class Dashboard extends React.Component{
>  7 |   const [tdata,setTdata] = React.useState([]);
     |         ^
   8 | 
   9 |   info = async () => {
  10 |     try {

1 Answer 1

1

You can't use React hooks in a Class-Based component, change your class into a pure functional component like this:

import React, { useEffect, useState } from "react";
import Table from "./Table";
import Nav from "./Navi";
import TemplateList from "./TemplateList";
import { Tab, Tabs } from "react-bootstrap";

const Dashboard = (props) => {
  const [tdata, setTdata] = useState([]);

  const info = async () => {
    try {
      const response = await fetch("http://localhost:8080/dashboard");
      const dataServer = await response.json();
      setTdata(dataServer);
    } catch (err) {
      console.error(err.message);
    }
  };
  console.log(tdata);

  useEffect(() => {
    info();
  }, []);

  return {
    <div>
       /* your JSX here */
    </div>
  };
};

More about hooks here: https://reactjs.org/docs/hooks-intro.html

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

Comments

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.