The integration of lodash debounce with a NextJS function is failing with the error message "[TypeError: search(...) is undefined]

I've been developing a feature in NextJS that allows users to search for YouTube videos based on their input. In order to optimize API calls, I decided to implement lodash debounce with the useCallback hook. However, I'm encountering an issue where I keep getting the error message:

TypeError: search(...) is undefined

Below is the code snippet that I have written:

export default function VideoSearchComponent() {
  const [modalVisible, setModalVisible] = useState(true);

  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);

  const search = useCallback(
    debounce(async (keyword) => {
      const response = await fetch("http://localhost:3000/api/search/" + keyword); 
      const data = await response.json();
      return data;
    }, 500),
    []
  );

  useEffect(() => {
    if (searchQuery) {
      search(searchQuery).then((results) => setSearchResults(results));
      console.log(searchQuery)
      console.log(searchResults)
    } else {
      setSearchResults([])
    }
  }, [searchQuery])

  return (
    <Modal label={'Search for videos'} show={modalVisible} handleClose={() => setModalVisible(false)}>
      <div>
        <IoSearch size='1.25em' color={searchQuery ? '#000' : '#9ca3af'}/>
        <input type="text" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} placeholder="eg: 'Standup Comedy'"/>
      </div>
      <SearchResults results={searchResults}/>
    </Modal>
  )
}

Could someone please assist me in understanding why my search function is showing as undefined?

Answer №1

debounce will not return a value from the inner function unless you explicitly specify the leading: true option for it.

Therefore, the issue is not that your search is undefined, but rather that there is no promise and no then(...) returned from invoking search(...).

In any case, I recommend moving your setSearchResults inside the search function to avoid potential race conditions when a user quickly types and deletes a query.

Answer №2

If you want to optimize the usage of the debounced searchQuery, it's best to debounce the searched value rather than the function that makes the call. You can skip wrapping the fetch function in a React.useCallback and use it directly within your useEffect instead.

Consider utilizing the useDebounce hook for debouncing your search query efficiently.

 const debouncedSearchQuery = useDebounce(searchQuery, 500);

 useEffect(() => {
    if (debouncedSearchQuery) {
      fetch(`http://localhost:3000/api/search/${debouncedSearchQuery}`).then((data) => {
        console.log(debouncedSearchQuery);
        setSearchResults(data);
        console.log(searchResults);
      });
    } else {
      setSearchResults([]);
    }
  }, [debouncedSearchQuery]); // Trigger effect only when debounced search term changes

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

Does TypeScript lack awareness of type checking within nested functions?

Currently, I am using TypeScript with React and encountering a particular issue. Below is a function I have created to ensure that the variable 'arr' is an Array and not empty. export const isNotEmptyArr = (arr?: unknown[]) => { return Arra ...

Error encountered while executing npm run dev in the node module for next.js: token not recognized

Setting up a new Next.js project has been my latest task. I followed the instructions in the documentation exactly and used this command line: npx create-next-app@latest nextjs-blog --use-npm --example "https://github.com/vercel/next-learn/tree/maste ...

Error: EsLint detected that the classname is not a valid Tailwind CSS class

I am encountering an EsLint error indicating that "className is not a TailwindCSS class" after incorporating custom classes like colors into my tailwind.config.js file. Despite this, I am unsure about how to resolve this issue. Shouldn't EsLint recogn ...

Issue arising from background change upon component focus

My component needs to change its background color when focused, but for some reason it's not working. The hover effect works fine, but the focus doesn't. Can anyone assist me with this issue? import { CardContainer } from './styles' in ...

Error in React+Redux: Trying to access the "address" property of a null value is not permitted

I am new to using react and encountering an issue with my ecommerce app. The app runs smoothly until I log out and then log back in at the shipping address page, which triggers the following error: TypeError: Cannot read property 'address' of nu ...

Oops! Looks like there was an error. The text strings need to be displayed within a <Text> component in the BottomTabBar. This occurred at line 132 in the

My app includes a bottomTab Navigation feature, but I encountered an error: Error: Text strings must be rendered within a <Text> component. This error is located at: in BottomTabBar (at SceneView.tsx:132) in StaticContainer in StaticCont ...

The Server Components render encountered a glitch

Screenshot of the errorI am encountering a strange error only in the production environment. The lack of additional information leads me to believe it may be due to security measures put in place for production. Unfortunately, I have been unable to repli ...

Issue with setting the state of form data in React Material UI Dialog when updating it

There seems to be a issue with the dialog form where new data selection results in displaying the original data incorrectly. Only by closing and reopening the dialog does it show the correct values. I suspect there might be some trickery going on with the ...

What is the best way to conceal the options menu for a specific column in the MUI datagrid?

I am utilizing the community version of MUI x and I am searching for a way to hide the menu options from just one specific column, rather than all columns. I would like the menu to still show up for the other columns, but for this particular column, I need ...

`The logo does not dim when the popup is displayed`

I'm currently experiencing an issue with pop-ups on my page - when they appear, they create a shade over all elements of the page except for my two logos and are displayed with a border around them. Here's what my page looks like before the popu ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...

Guide on resolving ENOENT Error during React installation in Windows Subsystem for Linux

Currently, I am delving into the world of React app development using WSL (Windows Subsystem for Linux). As a newcomer to this technology, I have been working on creating an app located in my D drive (/mnt/d). Node has been successfully installed via NVM a ...

Initiate an interactive pathway using @

Within my NextJS application, utilizing the pages router, there is a specific file called @[username].tsx. This format mirrors YouTube's user profile links and resides in the pages folder. Despite this setup, attempting to access /@lordsarcastic resul ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

What is the best way to utilize withStyles in order to render a React component?

My question doesn't concern exporting, but rather how to return a React object with injected CSS. I am attempting to achieve the following: return ( withStyles(this.props.style)(<Component {...params}/>) ); The goal is to return Component wit ...

Discover the hidden truth: Unveiling the enigma of React

I'm currently learning React and I've been working on some apps to enhance my skills and deepen my understanding. Right now, I am facing a challenge where I need to incorporate the logged user information into the Redux state. However, whenever I ...

Encountering a 404 Error while using my Next.js 13 API Route

I recently forked a project and attempted to set up an API Endpoint for my CRUD operations with a database. However, I encountered difficulties in accessing my endpoint. Even with a test on a dummy API https://jsonplaceholder.typicode.com/todos, I still re ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

React isn't showing the image

While working on my React website, I encountered an issue where my local image is not displaying. I am using props to pass properties from Cards.js to CardItem.js and everything displays correctly except for the image. I'm not sure what the problem co ...

What is the procedure to switch the state using useState when an event is activated?

I'm trying to learn React by implementing a basic shop. One idea I had was to have multiple product images and when a user clicks on an image, it flips around to display additional information such as comments and ratings for the product. For this pr ...