Format JSON Data to Display Results
Learn to format JSON returned by the WordPress REST API.
We'll cover the following...
Formatting JSON data
Open the Search.js
file from the modules folder inside the src folder. The Search
class has a sendSearchRequest
method which sends a request to the WordPress REST API. We will work on displaying the results in this lesson.
In the previous lesson, we displayed the title of the posts on the console. Now we will adjust the markup of the search-results
div to display the title under the input box. The sendSearchRequest
method from the last lesson is reproduced below:
sendSearchRequest(){fetch(siteData.root_url+ '/wp-json/wp/v2/event?search='+this.searchInput.value).then((response)=>{return response.json();}).then((data)=>{console.log( data.map(function(element){return `${element.title.rendered}`;}));});this.isSpinning = false;}
Recall, that the <div>
that displays the search results is contained in the searchResults
property.
constructor(){//other propertiesthis.searchResults = document.querySelector("#search-results");//...}
Open the terminal in VS Code by clicking the "View" option and choosing "Terminal." Run the start script using the
npm run start
command. The start script will watch for any changes in the code and recompile it.
We will target the innerHTML
property of searchResults
to output ...