Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client'
async function Teachers (){
    const response = await fetch('http://localhost:8000/teachers',
        
    })
    const data = await response.json();
    const [showNames , setShowNames] = useState(false);

    // Unable to use button due to error
    const teacherHandler = ()=>{
    setShowNames (!showNames)
}
    return (
        
    <div className="mt-10">
        <div className=" text-center font-DanaDemiBold text-3xl text-white">
            <h1 className="w-full bg-slate-900 mb-5">Teachres</h1>
            <button onClick={teacherHandler} className="p-3 bg-green-600 rounded-lg mt-5 hide-button">Show/Hide Teachers Name</button>
     );
        </div>
        <div className=" flex justify-center items-center flex-wrap p-2 gap-3 my-10 ">
            {
            !showTeachers?null :
            data.map(item=>(      
            <div key={item.id} className=" w-1/3 h-[300px] flex justify-between items-center shadow-lg bg-slate-300 rounded-lg teacher-card">
                <div className="flex flex-col m-10 gap-y-5">
                <div className="flex gap-x-2">
                    <h3> Name: </h3>
                    <span>{item.firstname}</span>
                    <span>{item.lastname}</span>
                </div>
                <div className="flex gap-x-2">
                    <h3>    Email: </h3>
                    <span>{item.email}</span>
                </div>
                <div className="flex gap-x-2">
                    <h3>  Date of Birth: </h3>
                    <span>{item.birthDate}</span>
                </div>
                <div className="flex gap-x-2">
                    <h3>   phone: </h3>
                    <span>{item.mobile}</span>
                </div>
                <div className="flex gap-x-2">
                    <h3>     Address: </h3>
                    <span>{item.address}</span>
                </div>
                </div>
                <div className="w-36 h-36 m-10">
                    <img className="rounded-full" src={item.profileImg} alt="profile"/>
                </div>
            </div>
     ))}
   </div>
    </div>
    
    )
}

export default Teachers;

Thank you for your assistance. I am facing difficulties using the button and its corresponding function due to an error message indicating that async/await is not yet supported in Client Components, only Server Components.

Answer №1

Next.js does not support async Client component, so one alternative is to consider using a server component instead. However, it's important to note that server components do not support event listeners.

To work with async in a client component, the simplest approach is to utilize useEffect to manage side effects and then update the state with the retrieved data.

Note: When interacting with APIs, always handle errors appropriately. Placing console.error within a Try-Catch block may not be sufficient.

"use client";
function Teachers() {
  const [showNames, setShowNames] = useState(false);
  const [studentsData, setStudentsData] = useState();
  // Utilize useEffect to call async function
  useEffect(() => {
    getData();
  }, []);

  async function getData() {
    try {
      const response = await fetch("http://localhost:8000/teachers");
      const data = await response.json();
      setStudentData(data);
    } catch (error) {
      console.error(error);
    }
  }
  const teacherHandler = () => {
    setShowNames(!showNames);
  };
  return (
    <div className="mt-10">
      <div className=" text-center font-DanaDemiBold text-3xl text-white">
        <h1 className="w-full bg-slate-900 mb-5">Teachers</h1>
        <button
          onClick={teacherHandler}
          className="p-3 bg-green-600 rounded-lg mt-5"
        >
          Show/Hide Teachers Name
        </button>
        );
      </div>
      <div className=" flex justify-center items-center flex-wrap p-2 gap-3 my-10 ">
        {!showTeachers
          ? null
          : studentDatas.map((item) => (
              <div
                key={item.id}
                className=" w-1/3 h-[300px] flex justify-between items-center shadow-lg bg-slate-300 rounded-lg  "
              >
                <div className="flex flex-col m-10 gap-y-5">
                  <div className="flex gap-x-2">
                    <h3> Name: </h3>
                    <span>{item.firstname}</span>
                    <span>{item.lastname}</span>
                  </div>
                  <div className="flex gap-x-2">
                    <h3> Email: </h3>
                    <span>{item.email}</span>
                  </div>
                  <div className="flex gap-x-2">
                    <h3> Date of Birth: </h3>
                    <span>{item.birthDate}</span>
                  </div>
                  <div className="flex gap-x-2">
                    <h3> Phone: </h3>
                    <span>{item.mobile}</span>
                  </div>
                  <div className="flex gap-x-2">
                    <h3> Address: </h3>
                    <span>{item.address}</span>
                  </div>
                </div>
                <div className="w-36 h-36 m-10">
                  <img
                    className="rounded-full"
                    src={item.profileImg}
                    alt="profile"
                  />
                </div>
              </div>
            ))}
      </div>
    </div>
  );
}

export default Teachers;

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

effective method for iterating through JSON data using JavaScript or jQuery

Upon receiving a JSON object from the server, it looks like this: { "0": { "id": "1252380", "text": "This whole #BundyRanch thing stinks to high hell. Can it be a coincidence that Harry Reid n his son have a financial interest in this land?", ...

The code encountered a parsing error at 11:1, due to the presence of

I'm having trouble with this code. I've searched for answers but haven't found any solutions. Here is the error message: 11:1 error Parsing error: Unexpected token } ✖ 1 problem (1 error, 0 warnings) npm ERR! code ELIFECYCLE npm ERR! ...

Difficulty in jQuery's clone() function: cloning an input element without its value

I have successfully implemented jquery's .clone() method, but I'm facing an issue where the value of the previous input field is also getting cloned along with it. How can I prevent this from happening? Below is my code snippet: function addrow ...

Using Jquery Ajax to Develop Laravel Dropdown Selection with Cascading Feature

I have been working with Laravel 5.6 and encountered an issue with my dropdown selection. Although I selected a province from the dropdown menu, the city menu did not display the corresponding cities. Below is the controller code that I am using: public f ...

Determine the vertical dimension of a child division once it has been integrated into an HTML document

My goal is to create a website with multiple pages without having to recreate the toolbar for each page. To achieve this, I have created a separate HTML file and CSS file specifically for the toolbar. On each page, I simply import the toolbar using the fo ...

What is a method to mimic the presence of JavaScript using PHP Curl?

Is it possible to parse HTML code from a webpage using PHP Curl even if there is an error message stating that JavaScript is required to access the site? Can PHP Curl be used to enable JavaScript on a webpage? ...

Generating an HTML version of a specific nextJS page by clicking a button that includes constantly changing data

I have a current project where I am tasked with filling a template.tsx file with the information gathered from a form, and then using that data to create an HTML file which can be downloaded to the user's device. Does anyone know how I can accomplish ...

Using the TIMESTAMP data type in PostgreSQL and getting the most out of it

After saving a Luxon datetime value in a TIMESTAMP(3) type column in a postgres database, I encountered difficulty using it for various operations like converting time zones. Despite creating the object with the code snippet below: const { DateTime } = req ...

The function GetURLParameter(sParam) is displaying %20 as blank space in the webpage

I am facing an issue with a code that pulls URL parameters into the landing page. The problem is that it is including white spaces as %20. For example, if my URL parameter is: example.com/?title=my website, it would display my%20website on the page inste ...

Tips for Showing Certain Slides When the Page Loads

When using jQuery filter effects to organize div slides on a page, I encountered an issue where all the divs containing different slides are displayed on page load instead of just the default chosen ['active'] div. The filter effect itself is fun ...

How can I use JavaScript to find a keyword on a webpage that is not located within an <a> tag or its href attribute?

I'm on a mission to locate a specific keyword within a webpage. Sounds simple, right? Well, here's the tricky part - I need to disregard any instances of this keyword that are nested within an <a> tag. For example: <p>Here is some s ...

Launch both client and server simultaneously with a single command by utilizing Vue-cli and Webpack

Currently, I am setting up a Vue client with Vue-cli 3 that utilizes Webpack. (To start the client, I run "yarn dev --open") In addition, I am developing a server with an API for the client. (To run the server, I execute "node server/server.js") Is th ...

VueJs Ellipsis Filter: Enhance Your Texts with

Using Vue.JS, I am dynamically injecting text content into a DOM element. <article>{{ movie.summary }}</article> My goal is to implement an auto-ellipsis filter. Essentially, the code would look like this: <article>{{ movie.summary | e ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...

Can you explain the process of implementing a conditional render with three parts in React?

Currently, I am attempting to implement a conditional render but encountering some issues. Is it achievable? location: `${props.off_campus_location ? ( `${props.off_campus_location}` ) : ( `${props.campus_location.name}` ) : ( `${props.location_type}` )}` ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

npm installs a multitude of dependencies

Recently, I purchased an HTML template that includes various plugins stored in a directory named bower_components, along with a package.js file. While trying to add a new package that caught my interest, I opted to utilize npm for the task. Upon entering ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

methods for efficient set computations

I have a collection of sets in the format (a,b) which are as follows: (2,4) (1,3) (4,5) (1,2) If I am given a pair like <2,1>, I want to identify all sets in the collection where 2 or 1 is the first element. In this case, it would be (2,4), (1,3), and ...

What are the steps to utilizing an npm package that simply encapsulates my JavaScript code?

Our current npm package is designed for clients working on ES6-based projects, such as React. The main index file of the package looks like this: export function ourFunction() { } Clients import this function using the following syntax: import { ourFunc ...