How to Query a Database With a Search Bar: React App/Hooks

I recently created a project where I had to query a API from a search bar. Building it out was very fun and the practice is quite common, which can only mean one thing: make a blog post on it. Let’s get into my step by step process of building it out.

The Form

Image for post
Image for post
Image for post
Image for post

Handling the Submit

Here is my handleSearch Function. There is a few things going on here so let’s break it down. I am using the useRef hook to handle my user input on the form. You could do this with the onChange event, but I have been learning about hooks and useRef makes input forms too easy to ignore it. So, first I create the ref and assign it the value query. For this to work I have to pass this reference to the form as you see in the inputRef={query} statement.

Image for post
Image for post
const queryVal = query.current.value

The Fetch Request

Note: ignore all the state besides movies.

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store