Next.js Discord

Discord Forum

async/await is not yet supported in Client Components, only Server Components.

Answered
Nile Crocodile posted this in #help-forum
Open in Discord
Nile CrocodileOP
i have parent component which have input field and child component .
in Child component a fetch req is made depending on data entered in the Input Field of parent component.
so i made parent component as client component using "use Client", do which am getting above error
Answered by ᴉuɐpɹɐɐ
you cant put async server component inside client component. you can only pass server component into a client component

you have two options:
1. either refresh the page so that the server component gets updated
or 2. handle the data update in the client after user types in the input
View full answer

86 Replies

Sanderling
can you show some code
@Sanderling can you show some code
Nile CrocodileOP
"use Client "
const parentCompnent=() => {
const [searchTerm, setSearchTerm] = useState('');
const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
setSearchTerm(event.target.value);
};

return (
#Unknown Channel
<Input type="text"
placeholder="Search businesses..."
value={searchTerm}
onChange={handleSearch}
/>

<ChildComponet searchTerm={searchTerm} catergory="generalstore" />
</div>
</>
);
};

const ChildComponet: React.FC<ChildComponentProps> = async({ searchTerm, catergory }) => {

const businesses: Business[] = await getBusinessesByCategory(catergory) || [];
@Sanderling can you show some code as well how the fetch is made in child component?
Nile CrocodileOP
const businesses: Business[] = await getBusinessesByCategory(catergory) || []; am making fetch
Sanderling
create an a file for example called actions.ts, inside the file put a "use server" on top, then create an async function there that does the fetching. Then import the function inside your child component and use it
what are you trying to do
@ᴉuɐpɹɐɐ what are you trying to do
Search bar + searching for things depending on that client side state. I gave them a link showing exactly how to do that but they didn’t seem to care so…
Nile CrocodileOP
i have client component which hold input text/search in it and a server component server component is responsiable to render the list my making a fetch and when user perform search on input. the input value in parent component (client compont) is passed to child Component (server) @joulev
@ᴉuɐpɹɐɐ what are you trying to do
Nile CrocodileOP
pass the state of client component to its child( serer compnent) in child component we are fetch data
what does your code look like
where the error happens
Nile CrocodileOP
await/asyc can not be a part of client compoent


as my parent compent is client
child is server

const parentCompnent=() => {
const [searchTerm, setSearchTerm] = useState('');
const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
setSearchTerm(event.target.value);
};

return (
#Unknown Channel
<Input type="text"
placeholder="Search businesses..."
value={searchTerm}
onChange={handleSearch}
/>

<ChildComponet searchTerm={searchTerm} catergory="generalstore" />
</div>
</>
);
};

const ChildComponet: React.FC<ChildComponentProps> = async({ searchTerm, catergory }) => {

const businesses: Business[] = await getBusinessesByCategory(catergory) [];



const filteredproduct = !searchTerm
? products
: products.filter((product) =>
products.productName.toLowerCase().includes(searchTerm.toLowerCase())
);

return (
#Unknown Channel
<Suspense fallback={<div>Loading...</div>}>
{filteredProduct?.map((product, index) => (
<Card key={index} product={product} />
))}
</Suspense>
</>
);
};


error in childcompoent : const businesses: Business[] = await getBusinessesByCategory(catergory)
[];
???
Nile CrocodileOP
@ᴉuɐpɹɐɐ posted full code
@Nile Crocodile <@194128415954173952> posted full code
can you write it in code blocks please, like this

```tsx
paste code here
```
Nile CrocodileOP
sure
"useclient"

const  parentCompnent=() => {
 const [searchTerm, setSearchTerm] = useState('');
const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(event.target.value);
  };

 return (
    <>
          <Input type="text"
            placeholder="Search businesses..."
               value={searchTerm}
                onChange={handleSearch}
               />

           <ChildComponet searchTerm={searchTerm} catergory="generalstore" />
      </div>
    </>
  );
};


const ChildComponet: React.FC<ChildComponentProps> = async({ searchTerm, catergory }) => {

  const products: Products[] = await getproductsByCategory(catergory)  [];



  const filteredproduct = !searchTerm
    ? products
    : products.filter((product) =>
        products.productName.toLowerCase().includes(searchTerm.toLowerCase())
      );

  return (
    <>
    <Suspense fallback={<div>Loading...</div>}>
      {filteredProduct?.map((product, index) => (
        <Card key={index} product={product} />
      ))}
    </Suspense>
    </>
  );
}; 
const products: Products[] = await getproductsByCategory(catergory) [];
i have error here
Nile CrocodileOP
@ᴉuɐpɹɐɐ posted formated code
@Nile Crocodile <@194128415954173952> posted formated code
you cant put async server component inside client component. you can only pass server component into a client component

you have two options:
1. either refresh the page so that the server component gets updated
or 2. handle the data update in the client after user types in the input
Answer
Nile CrocodileOP
lets me try 1 , with 2 option data is fetched in server component that i that can we may need to transfer data to parent client and handle data and pass it back
@ᴉuɐpɹɐɐ you cant put async server component inside client component. you can only pass server component into a client component you have two options: 1. either refresh the page so that the server component gets updated or 2. handle the data update in the client after user types in the input
Pacific sandlance
Does that mean this example wouldn't work if there was a fetch inside of SearchResults?

https://react.dev/reference/react/useDeferredValue

export default function App() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  return (
    <>
      <label>
        Search albums:
        <input value={query} onChange={e => setQuery(e.target.value)} />
      </label>
      <Suspense fallback={<h2>Loading...</h2>}>
        <SearchResults query={deferredQuery} />
      </Suspense>
    </>
  );
}
Pacific sandlance
I figured the example is not fetching, but Wouldn’t suspense be doing nothing if there’s no async inside of it?
Does that mean this example wouldn't work if there was a fetch inside of SearchResults?
This would work and this is the second option i put in my message above
there is saync
Its not an async component but the use hook resolve any promise inside there (fetchData) and use the suspense if the promise is still awaiting
in this case fetchData is an async function that fetches data FROM the client side
but you can do this with normal react without use and without suspense and would be the same as handling the change and the data fetching in the client side (not in the server)
Pacific sandlance
Okay got it. Thanks
Nile CrocodileOP
@ᴉuɐpɹɐɐ event 1 option did not work . and option is going to multiloops.

so i tried to https://github.com/rollingsxshi/next14-discuss/blob/main/src/components/topics/topic-create-from.tsx#L16 where he moved code to different file under "use serve". i did not get that exactly gng here
option 1 should work, i use it all the time
Nile CrocodileOP
@ᴉuɐpɹɐɐError: async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding 'use client' to a module that was originally written for the server.
you need to put server component from a server component
you cant put it inside a client component
I put searchTerm in the searchParam using nuqs.
when client edit the searchTerm, it edits the searchParam.

You can use nuqs to get the searchParams in page.tsx (server component) and pass it down to your async server component
if you dont want to refresh the whole page then you could use option 2
option 2 is classic react so you might want to search up how to trigger client side fetch when the searcHTerm is updated
Nile CrocodileOP
as part of option 2 i just make child also client and calling in useEffect its working but i create a new file action.ts with "use server" on top and added call it worked.
ok so all good?
Nile CrocodileOP
yes, it fixed issue but it turn as client component and request is happen on client
Thats option 2
If you want option 1 then you need to move the component a bit
Nile CrocodileOP
what would be the work around for it
export default Page({ searchParams }){
  const search = searchParams.search
  const data = await getData(search)

  return (
    <>
      <SearchField />
      <Result data={data}/>
    </>
  )
}
Nile CrocodileOP
so with the above option , with onchange or on submit its call the getData api correct
and by default if searchParamsis empty it call getData with ""
onSubmit, you router.push() to the same url with searchparam. This wont call the getData api.
The page refresh will refresh the server component and call getData
its easier to handle with https://nuqs.47ng.com/docs/server-side
Nile CrocodileOP
got its so using nuqs make us to skip use client
it is just refreshing the page
and retrigger rerender
which honestly, client-side handling is way more efficient (option 2)
since you can debounce it and not spam your server load
Nile CrocodileOP
yes, but am worried that option 2 bumps client with json data from api call
wdym?
Nile CrocodileOP
wdym means
yes
@Nile Crocodile wdym means
what do you mean?
@Nile Crocodile this do same a nugs?
nuqs have 2 option
either handle it in the client or you can also make it read in the server
because it reads searchparams in the server
and then change the searchparam in the client via <Search>
Nile CrocodileOP
ok will it re-fetch data with new search
yes because everytime you change the search, you rerender the whole page
the whole
page
Nile CrocodileOP
ok
option 2 is better i guess
ontions 2 to avoid refecth
1. to have it as serve component
option 2 is not to avoid refetch, but to avoid rerendering the whole page
thereby reducing server load
option 1 is correct, have it as server component. everytime search changes it will refetch the whole page, and the data too
Nile CrocodileOP
yes, my goal to have server handle with less data fetch calls
Nile CrocodileOP
sure i wll