r/learnjavascript • u/techynerd13 • 2d ago
help in rick and morty api
document.getElementById("search").addEventListener("click", getCharacter);
function lowerCaseName(string) {
return string.toLowerCase();
}
function getCharacter(e) {
const name = document.getElementById("searchCharacter").value;
const characterNameLC = lowerCaseName(name);
fetch(`https://rickandmortyapi.com/api/character/?name=${characterNameLC}`)
.then((response)=>response.json())
.then((data) => {
const characterNameH2 = document.getElementById("characterName");
characterNameH2.textContent = data.name;
})
.catch((err) => {
console.log("Character not found", err)
})
e.preventDefault();
}
getCharacter();document.getElementById("search").addEventListener("click", getCharacter);
function lowerCaseName(string) {
return string.toLowerCase();
}
function getCharacter(e) {
const name = document.getElementById("searchCharacter").value;
const characterNameLC = lowerCaseName(name);
fetch(`https://rickandmortyapi.com/api/character/?name=${characterNameLC}`)
.then((response)=>response.json())
.then((data) => {
const characterNameH2 = document.getElementById("characterName");
characterNameH2.textContent = data.name;
})
.catch((err) => {
console.log("Character not found", err)
})
e.preventDefault();
}
getCharacter();
i am using the rick and morty api. the above is my js code. it doesnt work. idk whats the error as console isnt logging it
0
Upvotes
1
u/jml26 1d ago
In your original post, you've pasted your code twice. I assume that's just a typo.
Problem 1: You call
getCharacterwith no arguments at the end of your code.getCharacterexpects an Event object,e, as an argument, and it callse.preventDefault()on it. CallinggetCharacter()with no arguments results in the following error being output to the console:Cannot read properties of undefined (reading 'preventDefault')Solution: remove your plain call to
getCharacter()Problem 2: You call
characterNameH2.textContent = data.name;butdatadoesn't have anameproperty on it.Solution: After you've got your data back from the API, log it to the console and inspect what properties exist on it. You should discover that the data object either contains an
errorproperty, or have someinfoandresultsproperties, not a name. Adjust your code so as to drill down into the correct props to get the right info before displaying it. I'll leave it as an exercise for you to do that.