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

Tips for displaying complex JSON structures in VueJS

I want to extract this information from a JSON dataset <ol class="dd-list simple_with_drop vertical contract_main"> <li class="alert mar" data-id="1" data-name="Active" style=""> <div class="dd-handle state-main">Active<span cl ...

Update the navigation logo while scrolling

My website has a scrolling navigation menu using Wordpress. The default logo color is green, but when the user scrolls, a white background appears. However, on specific screens, I need the initial logo to be white. I have managed to create an alternate na ...

Can Vue.js be paired with pure Node.js as a backend without relying on Express?

After successfully building a project with both vue js and node js, specifically with express, I'm curious if it's feasible to solely utilize node js without frameworks like express. ...

What is the correct way to invoke a function within jQuery?

There must be a straightforward solution to what appears to be a simple and regular task. Inside the $(document).ready() function, I aim to invoke a function with a jQuery object - specifically without attaching it to an asynchronous event like mouseover ...

Can an ID and a "<?php echo ''.$variable.'' ?>" be included in the same input or video tag?

I have a task where I need to insert various Ids into a single video input tag. Specifically, I need to include the player and its row ids from PHP in this format: <video preload controls playsinline id="player[<?php echo ''.$row5['id ...

What is the process for importing a JSON5 file in Typescript, just like you would with a regular JSON file?

I am looking to import a JSON5 file into a JavaScript object similar to how one can import a JSON file using [import config from '../config.json']. When hovering over, this message is displayed but it's clearly visible. Cannot find module & ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Selenium web driver showcases its capability by successfully launching the Firefox browser, yet encounters an issue with an invalid address

WebElement searchElement = driver.findElement(By.name("q")); searchElement.sendKeys("Selenium WebDriver"); searchElement.submit(); Displays "Search Results" public static void main(String[] args) { // TODO Auto-generated method st ...

Conditional Matching with Javascript Regular Expressions

My strings are formatted like this: #WTK-56491650H #=> want to capture '56491650H' #M123456 #=> want to capture 'M123456' I am trying to extract everything after the # character, unless there is a dash. In that case, I onl ...

What is the method for choosing an Object that includes an Array within its constructor?

Is there a way to retrieve a specific argument in an Object constructor that is an Array and select an index within the array for a calculation (totaling all items for that customer). I have been attempting to access the price value in the Items Object an ...

Customize MUI 5 input label background color for your own component

Struggling with overriding the background color for a MUI 5 input label on focus in a specific component? I successfully changed it to blue globally in my _theme.js file, but now need to make it red for my KeywordSearchTextField in index.js following MUI ...

I am encountering an issue with Angular where the following error message is displayed: "src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'"

This code snippet is from my app.component.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...

Adding information into sqlite from a json document

There seems to be an issue here, I'm unable to make an insertion: $.getJSON('file.json', function(data) { tx.executeSql("INSERT INTO table (DATE, LIB, BID) VALUES("+data.date+","+data.Lib+","+data.BID+")"); }); ...

Express.js | Utilizing express.Router and handling route parameter inputs

I'm currently facing an issue with a small program I'm developing to practice Express.js. The problem lies in a separate router that is supposed to send a specific response based on the route. For example, when navigating to "/santiago", it shou ...

I'm currently facing an issue with toggling the visibility of a div using JavaScript

In my attempt to create a unique custom select menu using html, css, and javascript, I encountered an issue with toggling the display style of the div containing the options when clicking on the button (in this case, an arrow). HTML: <ul class="de ...

Tips for saving information from a textarea into an HTML file

I have a unique question regarding the usage of $fopen and $fwrite functions. My goal is to include a button named "save as HTML" below a textarea. Upon clicking this button, I want a popup box to appear mimicking the 'save as...' dialog window ...

Problem with React Router: Uncaught Error - Invariant Violation: The element type is not valid, a string is expected for built-in components

I am encountering an issue with react-router and unable to render my app due to this error. Here is a screenshot of the error I have searched extensively for a solution but have not been able to find anything useful. Any help would be greatly appreciated ...

Can different versions of Node be used simultaneously for various Node scripts?

Currently, I am utilizing nvm. Can a specific node version be used for a particular script? For instance... Using node 6 forever start -a -l $MYPATH/forever.log -e $MYPATH/err.log -c "node --max_old_space_size=20" $MYPATH/script_with_node_version_6.js U ...

Tips for reducing the JavaScript file size outputted by a liquid template generator

Currently, I am working on enhancing the performance of my Shopify website and GoogleSpeed Insights is suggesting that I minify css and js files. However, the recommended files are all created by the liquid template generator, making it challenging to uti ...

Error: The route cannot be established within an asynchronous function

The following code snippet is from the api.js module, responsible for creating a test route: 'use strict'; module.exports = function (app) { console.log("before route creation"); app.get("/api/test", (req, res) => { ...