Topic: MDBAutocomplete : internal server error
Hy, I am using nextJs 14. and I have an issue with MDBAutocomplete component. My page.tsx is in the app directory : /app/toto/page.tsx It only loads a simple component which is a client component. And we have a GET error in the client console. - GET http://localhost:3000/toto 500 (Internal Server Error) I do not understand why ? Thanks.
// /app/toto/page.tsx
import Autocomplete from "./autocomplete";
function page() {
return (
<Autocomplete />
);
}
export default page
// /app/toto/autocomplete.tsx
"use client";
import { useState } from "react";
import { MDBAutocomplete } from "mdb-react-ui-kit";
const defaultData = [
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
];
const Autocomplete = () => {
const [data, setData] = useState(defaultData);
const onSearch = (value: string) =>
setData(
defaultData.filter((item) =>
item.toLowerCase().startsWith(value.toLowerCase())
)
);
return (
<MDBAutocomplete id='test' name='test' data={data} label='Example label' onSearch={onSearch} />
);
};
export default Autocomplete;
Mateusz Lazaru staff answered 1 year ago
The problem is a known issue in Next.js, and it appears, because the component code is being evaluated on the server side. The component uses such objects as IntersectionObserver
, window
, document
etc. but they are not defined on the server side. That's why the server fails and the browser shows the error message.To learn more about it, google window is not defined nextjs.
Of course, there are ways to fix it. I personally like this workaround:
"use client";
import { useEffect, useState } from "react";
import { MDBAutocomplete } from "mdb-react-ui-kit";
const defaultData = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];
type ClientOnlyWrapperProps = {
children: React.ReactNode;
};
// notice that ClientOnlyWrapper is a reusable component and should work fine with any component and any library
const ClientOnlyWrapper = ({ children }: ClientOnlyWrapperProps) => {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
return <>{isClient ? children : null}</>;
};
const Autocomplete = () => {
const [data, setData] = useState(defaultData);
const onSearch = (value: string) =>
setData(defaultData.filter((item) => item.toLowerCase().startsWith(value.toLowerCase())));
return (
<ClientOnlyWrapper>
<MDBAutocomplete
id="test"
name="test"
data={data}
label="Example label"
onSearch={onSearch}
/>
</ClientOnlyWrapper>
);
};
export default Autocomplete;
cariforef free answered 1 year ago
Ok, thanks Mateusz. It works perfectly. My autocomplete field finnally works well ! have an happy 31st december night ! Didier
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- ForumUser: Free
- Premium support: No
- Technology: MDB React
- MDB Version: -
- Device: -
- Browser: -
- OS: -
- Provided sample code: No
- Provided link: Yes