Skip to content
Advertisement

How do I filter Fetch API results with a search bar in vanilla JS?

I’m really new to javascript. I’m trying to setup a page that fetches from a placeholder API(https://jsonplaceholder.typicode.com/posts) and displays the Title, Author(which I had to add) as well as the Body. I’m also trying to give the ability to use the search bar to filter the results by userId. I got some help a few days ago getting the data from the API to show on my page but I’ve been struggling to get the search bar to work. Doe’s anyone have any ideas on how to get it to work? Any help is greatly appreciated.

Edit: I thought I found a solution but I can’t seem to get it to work. I updated the code to reflect what I’m trying. Sorry if I’m missing simple stuff.

JavaScript
JavaScript

Advertisement

Answer

Let’s take a look at your code: The below code performs a PATCH request, meaning it updates the data of a post, in your case by adding a name. Afterwards, it returns the post its updated data.

JavaScript

If we take a closer look at the api it’s returning data, we see that a userId is already defined. This means the user (which, in your case, is the author) can be retrieved from another api endpoint (https://jsonplaceholder.typicode.com/users/${post.userId}), so no need to use the FETCH request. Instead, we’ll first GET the posts, then GET the users, and combine them in a nice list post_data for reference:

JavaScript

Aaah, that’s better! Now we want to be able to filter these results based on author. Since you ask for this to be done in javascript, I’ve adjusted your html from:

JavaScript

to

JavaScript

The php link is removed (since i don’t think you’re using php). Note that I’ve added an id to both the <input> and <button> tag. We’ll use those to identify our button.

We can finally try to filter our results:

JavaScript

working example on codepen

Advertisement