JS Live Search Filter Uncaught in promise error

4492 views javascript json
3

I'm working through a live search bar with javaScript and JSON and am getting this error and I can't figure it out:

Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
    at outputHtml (main.js:35)
    at searchStates (main.js:19)

I have no idea why. Any help? Code:

const matchList = document.getElementById("matchList");

//search and filter data
const searchStates = async (searchText) => {
  const res = await fetch("../data/states.json");
  const states = await res.json();

  //find input matches
  let matches = states.filter((state) => {
    const regex = new RegExp(`^${searchText}`, "gi");
    return state.name.match(regex) || state.abbr.match(regex);
  });

  if (searchText.length === 0) {
    matches = [];
  }

  outputHtml(matches);
};

//show filtered results
const outputHtml = matches => {
  if (matches.length > 0) {
    const html = matches
      .map(
        match => `
        <div class="card card-body mb-1">
            <h4>${match.name} (${match.abbr}) <span class="text-primary">${match.capital}</span></h4>
            <small>Lat: ${match.lat} / Long: ${match.long}</small>
        </div>
        `
      )
      .join("");
    matchList.innerHTML = html;
  }
};

search.addEventListener("input", () => searchStates(search.value));

line 19 is the outputHtml(matches); and line 35 is matchList.innerHTML = html;

answered question

1 Answer

2

matchList is undefined please add condition to check it

if (matchList && matches.length > 0)

Or

matchList.innerHTML = html;

replace with

document.getElementById("matchList").innerHTML = html;

posted this

Have an answer?

JD

Please login first before posting an answer.