Quick Autocomplete App With JS & JSON
VloĆŸit
- Äas pĆidĂĄn 7. 09. 2024
- In this project we will build a simple web app that searches a JSON file using the Fetch API, Async/Await, Regex and high order array methods.
Sponsor: DevMountain Bootcamp
goo.gl/6q0dEa
States.json Gist:
gist.github.co...
đ Become a Patron: Show support & get perks!
/ traversymedia
Website & Udemy Courses
www.traversymed...
Follow Traversy Media:
/ traversymedia
/ traversymedia
/ traversymedia
JS starts around 6:40 if you want to skip the HTML....thanks for watching!
At work on Friday I did this the long way and outdated way following that WC3 Tutorial. I will change my code to something like this because this is more modern and easy to understand I could have done it this way but I just had to get something up and running. Thanks Brad. You are doing the Lord's work.
Hey man, thanks to you I am on my way to starting a career in a field of interest. Is there anyway one can contact you, maybe like Discord or something?
You are an absolute blessing to us who are self-taught.
You ought to recreate this in a bit more complicated way and create a rudimentary state method to explain how state is handled in higher level apps such as react. It would be an interesting lesson for beginners.
Make youtube series course on vuejs and d3js for data visualization . Love from Nepal
Next time use material theme inside vscode so it will be pleasing to the viewers eyes, the default theme looks ugly.
For those who have an error while fetching data:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
This is happening because fetch() fires up from index.htlml instead of main.js . Just delete from fetch request: "../" or put .html and .js files in same folder, this worked for me.
If we will look at Brad's Live Server URL we would see that index.html have no parent folder, so fetch can't execute request: "../".It can't go level up to parent directory because its don't exist on port 5501 in this case, so it works just OK in this video. My localhost look like this: 127.0.0.1:5500/JS/Autocomplition/index.html and it get error while fetching data from states.js, because fetch have place to go while executing this part of path: "../".
Thank very much. This help me with this tut and prior tut. Cheers!
Cheers mate!
dude thanks a lot
This!!
I noticed that matchList inerHTML does not reset when matches array is/gets empty. So, you should add this if statement in the searchStates function:
if (matches.length === 0) {
matchList.innerHTML = '';
}
this will clear the innerHTML in case the input does not match with the regex.
I tried it his way and your way and when I remove any search text, it still doesn't clear the matchList.innerHTML for me. However, if I clear it manually via the console, it works. Any ideas?
For those who have an error while fetching data:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
You just need to take out the "../" from fetch() method.
You can use like this: fetch('data/states.json');
This works here.
Thank you. : )
Someone pointed out that I am making a request with every input event fire. Here is some revised code...
const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
let states;
// Get states
const getStates = async () => {
const res = await fetch('../data/states.json');
states = await res.json();
};
// FIlter states
const searchStates = searchText => {
// Get matches to current text input
let matches = states.filter(state => {
const regex = new RegExp(`^${searchText}`, 'gi');
return state.name.match(regex) || state.abbr.match(regex);
});
// Clear when input or matches are empty
if (searchText.length === 0) {
matches = [];
matchList.innerHTML = '';
}
outputHtml(matches);
};
// Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
const html = matches
.map(
match => `
${match.name} (${match.abbr})
${match.capital}
Lat: ${match.lat} / Long: ${match.long}
`
)
.join('');
matchList.innerHTML = html;
}
};
window.addEventListener('DOMContentLoaded', getStates);
search.addEventListener('input', () => searchStates(search.value));
this revised js actually solved my "TypeError: res.json is not a function" bug that persisted from minute 4 till the end of this tutorial from the line:
const states = await res.json();
i have error on this line - const states = await res.json(); -
on res.json ();
Chrome Compiler says " Uncaught (in promise) SyntaxError: Unexpected end of JSON input at searchStates "
@@upload8722 this is happening because fetch() fires up from index.htlml instead of main.js for some strange reason. Just delete from fetch request: "../" or put .html and .js files in same folder, this worked for me.
this one actually quite better if you think about performance
Hi Brad, I'm having problem at the final state of this project, the browser is throwing an error message saying Uncaught TypeError: Cannot set property 'innerHTML' of null
at outputHtml (main.js:40)
at searchStates (main.js:25)
at HTMLInputElement. (main.js:45)
Thanks Brad...All your videos are very very good and helpful. And please do a video on SEO Brad...that would be nice.
brad , in one of his video already told that he really dont know how all this SEO works so maybe he will not make a video on something in which he is not an expert.
Thanks Brad! Because of your mern stack course I got first place in a local Bootcamp , thanks !!
Mansoor Mughal its getting updated Monday đ complete revamp
Traversy Media 1080p videos please !
I will name my first son after you, this saved my ass so badly, I haven't worked with fetch api in such a long time. I had no clue where to even begin to do this typeahead search from a local Json.
Had to adapt some of the code since I use TS and Angular but you are truly a lifesaver.
This is a great! I just wish it included a function to select the state so that you could complete the search. Afterall, we must assume that once they search they'll want to go to a page or resource.
I just spent a full weekend looking up the best way to do this and this is the simplest solution i've seen so far. THANK GOD WE HAVE BRAD
a very useful video, thank you buddy
short information for other users: If you want to search for only ONE keyword like "name" or "abb" or anything else, you also can use the html-tag : Load the json file with js > great a DOM with all the keyword options in your html document > choose your certain keyword option in the input tag by "keydown actions" or by the "button down arrow" in the right of the input > create a new "addEventListener() method" for the "key-enter" or "mouse-klick" action after the input is filled or one element of the list is selected > create a new DOM object like a or with all the json data of the selected keyword option. The is a very easy and useful html tag for a seach bar function ...
This is one channel that i dont even wait to watch the video before liking... You are awesome traverse
Great video , Iâm watching this from 16000 km from the US.
Hey Brad, you can actually use emmet in js. You just need to add this setting in your vs code setting.json
"emmet.includeLanguages": {
"javascript": "html"
},
Literally about to google that issue, cheers my dude
Thaks thats very useful
nice use of async/await, regex and template literals ;)
Yeah It's a very small project but I figured I would use a very modern syntax in a real situation to help others grasp
@@TraversyMedia I've also watched your full length Async JS and ES6 vids, so it was nice to see stuff applied in practice :)
Brad Traversy is a machine himself. Thanks for yet another super video. You are an inspiration to many upcoming developers.
Its 2020 and you're still impressing me with your old time knowledge. Genius! Kudos from Kenya Africa. I'll apply this to my new real life project and share it with you in a few days it should be up and running. Thanks again.
I always learn something. I liked the map with the html + join. Definitely adding that to the toolbox.
I vote up before I even watch it because it's Brad!
So true...!!
Thanks a lot, this tutorial appeared very useful for me. I've made a suggestion engine on Python with FastAPI that sends out suggestions to requests containing a prefix. So I wanted to make a decent web UI for this thing, and following this video I've managed to do it. Instead of fetching data from a JSON file I send a prefix to my script and it returns a JSON reply. The rest of the code is basically the same. This video is awesome and explained very clear, even for a Python-based guy who's not too familiar with JS
This was awesome! I googled and found a json file with the provinces of my country and I was able to follow and adapt the code in this tutorial very easily. You've convinced me to learn Bootstrap, at first I was skeptical but it's obviously a very powerful tool.
Wow I just started learning about Fetch API and Async/Await stuff.
Brad is always on point with the trend.
This is an excellent tutorial and has helped me build a search app for plants (instead of states). I'm trying to extend it just a bit by allowing the user to select which keyword in the json data to search on. For example, my json data has names like "Name", "Cultivar" and "Reference" each with their own values. I'd like to allow the user to select any of those json names (Name, Cultivar or Reference) on which to match. Here's the relevant code as it stands:
const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
let plants;
// Get plants
const getPlants = async () => {
const res = await fetch('data/plants.json');
plants = await res.json();
};
// Filter plants
const searchPlants = searchText => {
// Get matches to current text input
let matches = plants.filter(plant => {
const regex = new RegExp(`^${searchText}`, 'gi');
return plant.Name.match(regex);
});
As you can see, the search only uses "Name" for the matching. I'd like that to be variable based on user input (Name, Cultivar or Reference). Could anyone suggest how to do this or point me to an online reference that explains how to do this. Thanks!
Be honest, Im watching this completely new to this, trying to learn. This is another video for people who are at your level, not for people actually trying to learn.
I can't believe, what fantastic content Brad is uploading!
If you read this, thank you very much!
The very best wishes from Vienna :-)
Hi Brad , I was create project by this tutorial, tried think about every code parts and was search many information about methods on MDN and how these work behind the scene)
Thanks for u job man, it's really cool because when I'm watching your tutors, I'm learning how think algorithmically.
I was change some stuff, now not states but polish voivodeships)
great work by educating people, the code make sense as you describe it but could you create "part2" with refactoring? There are few parts that set up bad habbits:
#1 as the states.json data is still the same (and usualy is in autocomplete), you should load it once instead of every keystroke. Extra request for each key is not a good idea.
#2 "fail-fast" - if there is no input, you dont need to execute the filter loop (and save up some time), you can check for the length at the start and simply call outputHtml([]);
#3 prepare regular expression outside of the filter loop. Now you are preparing new regex for each iteration while you can set it up before loop once.
#4 as separation of concerns, clearing up the match-list should still be done in outputHtml function instead of extra condition in searchStates. In here, simple else case will do it. (this is first step for the separation, there are more candidates like preparing html vs altering dom)
optional #5 introduce debounce/throtle functionality to limit number of operation for keystrokes
keep up the good work!
Thank you so much , been trying all day with examples and no real tutorial other than yours. You explained everything really good, cheers mate.
Brad. I know it's a long time ago, but this video just saved my life. I got the basics from your fantastic udemy course on Javascript, but this was just the example I wanted.. Thanks again
Dude you cant imagine how good you are at explaining and showing things ;D im writting currently my bachelor thesis with typescript and after that I want to learn more about web development and in my TODO playlists are nearly all your videos.
Thank you for this brad. Love this little short projects(love the long one as well, dont get me wrong), where we can burst out a little app in just a half an hour, to brush up on the skills we need or learning something new. Cheers from Norway!
That is exactly why I create them. They're also fun for me :)
I had this for an interview. Brad is the best!!!!!!!!!
I did not know you could use an array to write html ! :O Nice method! Thanks Brad!
Liking before watching the video because it's Brad!
saved to my playlist before watching bcuz its brad.
Downloaded before watching, because it's bradđ
so you haven't seen it yet... too slow bruv
Thanks Brad again. very neat and useful weekend project. I like it so much ... perfect for Friday/Sat to commit 1 hr to do it while still able to take care of kids and family stuff.
That went over my head, but I still liked it. Gotta dive into some complicated stuff to get better. One thing only, I'd have loved for you to slow down a little bit and explain things with a bit more details. Unless, this is aimed intermediate/advanced people, then I understand.
I don't understand very well English but you are awesome, your videos are amazing and I love them. I could understand async/await with this video and I'm very grateful with you. I would wish had to know your channel 1 or 2 years ago jaja. Thanks!
Would it be more performant to do the api fetch once, and then have the "input" event merely do the filtering? Your code fires a new ajax request on every single keystroke. Or maybe that's the preferred method? I dunno.
Yes, you are correct. I guess I was just trying to make it as easy as possible. But check the pinned comment for the revised code.
Traversy Media hey brad, I have a error like ReferenceError: document is not defined
how can I fix it
@@TraversyMedia hey Brad! thanks for the awesome tutorial. As Chris said I'm having an issue due to that. Could you direct me to the revised code? Thanks!
@@TraversyMedia Any chance we could get that revised code? I'm trying to leverage this for filtering through an entire iTunes library, and it's very slow when it makes the request on every keystroke. I'm not sure of the best way to research this to get the solution I'm looking for.
@Traversy media plzzz provide the revised code i cant find it
You are so awesome! Brad.
thank you for all of your videos.
Love this small projcet!!!
Please do them often!
MR Brad you've done it again. To be honest all your content are always great, I mean really great and helpful, they also relates to real world projects. Thanks so much for this amazing project. I personally created my own project which I actually included the search engine but didn't know where to find a tutorial project related to what and how I actually want the search engine to function like. Until I found one from you today. I'm curious sir, incase I want the data from the JSON file/package to be specifically customized to my need, how do I do that please. Looking forward for your response sir!
Hi Brad... I just wanna thank you for courses... I learn so much evryday... God Bless !!!
you can do this more optimal.
now you fetch all data evety time when key press regards what you type. if you have milion records this may be veery slow.
second you fetch all data and then if value is empty you clear result. you better stop fetch data in that situation.
or for example you can fetch all data on start and then only filter it in thath event.
besides that very nice video đ€
You are actually right though...fetching it all the time maybe inefficient. But Im guessing he knew that. The major point I believe was that fetching a local jsom file with fetch api is very possible. That for me is enough to give this video a resounding A+ ...
Thanks Brad for everything
@@degraphe8824 I would have saved the states in a separate .js file (first line of that file would be "let states=...here comes the JSON data) and then use this variable in my main js file. Thus all the fetch stuff can be omitted.
Of course the newly created js file has to be linked in the html just like the main.js
In my opinion, it is the best guide on youtube)
Great video as always Brad but you can have (matchList.innerHTML = "";) in the else part of the outputHTML function instead of the searchText.length if condition for better functionality.
So short simple and useful. Great nuggets here right through. I wish I'd had this when I was getting started.
Great. It's important to remind us what you can do without any framework. Thanks
Yo Brad, no idea if somebody already pointed this out, but at the end of the video you mention to clear the innerHTML if the searchText is empty. A better solution for this would be to add an else statement to if (matches.length > 0) which makes sure that if the matches is an empty array the innerHTML is set to null.
The code would be like follows:
if (matches.length > 0) {
const html = matches.map(match => `
${match.name} (${match.abbr}) ${match.capital}
Lat: ${match.lat} / Long: ${match.long}
`).join('');
matchList.innerHTML = html;
} else {
matchList.innerHTML = null;
}
Great video as always anyway.
This is much more effective than what Brad did as it also makes sure that if the expression doesn't match then 'matchList' would disappear.
For example, with Brad's code, if I type 'Del', then Delaware pops up but if I continue with 'Delhi', then the Delaware card still remains.
Brad forgot to address that.
Thanks for the great work.
Selecting the suggesion and showing it in the text box is not in the code. Can you please include it.?
MAN, YOU ARE AWESOME!
Thank you so much, I've been using jquery autocomplete, but now i can do vanilla JS Baby!
One more tool for using in my dev days.
Thanks Bro!
wow!! no hablo ingles pero me ayudo muchisimo, muchs gracias por estos videos
Now this is possible natively with
Thanks for some much in depth and refreshing videos they motivate me to stay on top of things cheers Brad.
you prolly dont give a damn but does anybody know a method to get back into an instagram account??
I was dumb forgot my password. I would love any tricks you can give me
0:00 - 0:05 BEST 5 SECONDS
done and dusted thanks man you are a legend
ill watch before my breakfast !!!im in san francisco just yr video woke me up :)
You're a good teacher.Thanks Brad
There's no one like you Brad! :D
I have never watched any Brad's video and not learn something new
Thanks, Brad for the great video.
Question - what would be the best practice if the array or object of items is really massive? For example, if we want to use for autocomplete all cities of t world. I assume fetching whole such JSON would significantly hog the local memory.
Is there any way around it in terms of performance or is it better to load from the database in such a case?
Trying to do the same Mate, did you figure out yet?
Hi, great solution and well explained. One question though is what about the approach to selecting one of the options from the presented list?
Cool stuff, Brad. I implemented this feature at my job but using Elasticsearch to generate the autocomplete suggestions.
i have error on this line - const states = await res.json(); -
on res.json ();
Chrome Compiler says " Uncaught (in promise) SyntaxError: Unexpected end of JSON input at searchStates "
I'm getting this same issue any thoughts?
Make sure your JSON file is ok. The error says that your json file has syntax error
Thanks , I consume 2+ Hour for this error but i am always check main.js file.
Work on Firefox but Failed to to Load Fetch API Error on Chrome.
You make it look so easy. Great job... again
Thank you so much, it helped a lot, however Can you mention , how can I SELECT a line by clicking any results? to return that selected line's data back ? thanks (yeah I'm beginner lol)
Thank you for the tutorial. But Ä° have a question. Let's suppose that we have 50 thousand cities in that JSON file. Isn't that gonna be time consuming to await fetching all of them? Is there a way to deal with my problem?
Brad is truly a legend!
Is it possible to remake the same logic with a datalist element of html5?
I mean applying innerHtml function to put new options and values from server?
I made it with keyup and I got results than I updated my options and values with the new data but the list won't show up under my input text.!
I inspected Firefox and Chrome dev tools every thing is OK but the list still dummied or hidden.
Oh that map.join chaining stuff is freak-noice.
Simple and Elegant as always! Good stuff Brad.. and please do a SEO tutorial .. Regards from Sri Lanka
Hey Brad, Please make some videos explaining SEO. It would be very helpful for freelancers like us.
There's still one issue with the code i guess, suppose i search for "axzcib..." as soon as i type "a" it shows me states starting with "a..", but when i continue to type other letters such as x,z,etc the previous search result stays there which should go away as there's no state starting with axz... Can someone tell me how to fix this???
Such a good video.
Can you tell me how to write a regex for a string with whitespace? I have a JSON file with airports and sort by IATA codes and airport names. Until now, the match for the names throws me this: "TypeError: Cannot read property 'match' of null".
Awesome video, it's great you used pure javascript!
Hi! Beginner here :) i've been battling this error for 2 days...(in promise) TypeError: Cannot read properties of undefined (reading 'filter')
I get 304 in the response header, and i see the (lint validated) json data itself in the response ...what could i be doing wrong?
This approach seems very like React. I like it though. Clean and simple!
@Brad @Traversy Media This is a great tutorial! I have a great use case for it. However, there is one piece missing... once you select a state, how do you get one of the items in the filtered list to populate into an html table???
Just looking for it Brad đđ
Thank you man
I'm always being motivated by you, Thank you for providing that much useful content, sir.
thanks man small issue, it will bug out if you input some special characters
This is one of the coolest project
Thanks for the awesome video, i realised that with this method, user is unable to click the dropdown list or pressing down to select through the list. Is there a way to enable this?
Hello, have you solve this problem? User can click the dropdown list to select through the list.
I think the video is very good and easy to understand. The data is fetched and filtered, but how do I get an entry in the input field from the list? I would like to continue working with the data! A note or an addition to it would be very, very helpful. Thank you for your effort and the video! Thumbs up!
How do I make those results clickable and direct to a page ?
Hello, thank you for the video !
Thank you so much, Brad. Very informative!
Hi Brad, you've been doing this for a while now and I think you are pretty good, although I'm not qualified to judge. If you don't mind me asking, do you feel you are constantly improving, or do you just get to a guru level and kind of peak around there? If you are constantly improving, what have you learned recently? What do you think you still need to improve on?
I ask because sometimes I think I'm generally doing good, but then I pick up a platform like Magento, and realize I'm missing something that is making it really hard to learn. It would be good to intuitively know the weaknesses or areas I need to work on. Thanks.
This is an awesome feature! I want to create a music JSON file with Songs and Artists listed and allow users to search for either a song or an artist from an external webpage. Since this requires the index.html file to be opened via a Live Server for it to work, how can this feature be used by external users? Does this work without doing anything else if it's on an external published webpage?
thanks! question how selecton or clic of the list and write the input
Like your crash courses.thanks Brad
Thanks Brad.
Thank you Brad...This is truly awesome
Another great tut Brad, can you do a simple tutorial to convert js code/library into react compatible code using refs? I've looked it up a lot but nothing exists and the official doc is a bit too much to consume for a newbie like me đ©đ©
Hi, thanks for the good video.
I have a question, hope you can help me.
How can i make the search result clickable ?
I want to make it to give more info when user click the search result.
For example, when user type "ma", the search result would show maine, maryland, etc.
The user decided to know more about maryland. So when she click maryland, it would show new layer (not separated page about maryland, maine, etc. since making all the separated result page like maryland.html , maine.html, kinda waste space. ).
i think i can imagine how to make the new layer(maybe using css+js or open html on html( htmla(htmlb) sort thing), but i cant understand to make search result is clickable and use the current data from the clicked result to generate it's other data(json already added new data, just not showned on search) .
Maybe you could help me.
.
Thanks.
Thanks a lot Brad love your videos, one question though how would I do that matchList.innerHTML = html;
in React js?
How to select values from the list by key up and down , set autofocus to true so it will be more user friendly
how would you write :
search.addEventListener('input', () => searchStates(search.value));
as a normal function ?
Hi Brad ,what s the best way(tech that i can refer too) to convert data that i receive from an api in a visual graphic?. At the end i would like to show on a web page updating alone when time pass
Thanks! Today I've learned a new thing. â€ïž
Me too, i had never seen output html through map operator))
Hey brad or anyone viewing the comments, love the vid and got it working! Was wondering if you knew of a way to make the drop down floating above the other things on the page... I have it setup on a search engine type page with suggested links under and it pushes those links down and off the page, any suggestions would be great! Thanks
Great video Brad! BTW aren't you going to make some Angular videos in the nearest future?