Getting image from pokeapi - javascript

I am trying to display the image from pokeapi but I get an error when I input the name. When I input the number I do get the pokemon image after clicking twice. But when I search for another pokemon I get a number of the previous pokemon. I would appreciate the help on the proper way to display the image. Thanks.
Javascript:
HTML:
Display image:
I tried a few ways but cant seem to get it to work.

PokeAPI expects the input to be the name or ID of the Pokemon,try this code please
const pokemonInput = document.getElementById("pokemon-input");
const pokemonButton = document.getElementById("pokemon-button");
const pokemonImage = document.getElementById("pokemon-image");
pokemonButton.addEventListener("click", function() {
const pokemonName = pokemonInput.value.toLowerCase();
const apiUrl = `https://pokeapi.co/api/v2/pokemon/${pokemonName}/`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
const imageUrl = data.sprites.front_default;
pokemonImage.setAttribute("src", imageUrl);
})
.catch(error => {
console.error(error);
pokemonImage.setAttribute("src", "");
});
});

Related

Return multiple values from a Javascript function (OMDB API)

I've been trying to configure the OMDB API to return multiple values (multiple movies) on my webpage
However, I'm not sure how to go about this and how to display more than one movie
Can anyone tell me what I did wrong through this code? I'm still pretty new to coding and jumping through hoops trying to figure it out
fetch("https://www.omdbapi.com/?s=batman&apikey=API-KEY")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then(data => {
console.log(data);
displaymovie(data);
})
.catch((error) => console.error("FETCH ERROR:", error));
function displaymovie(data) {
const movie = data.Search[1];
const movieDiv = document.getElementById("movie");
const movieName = movie.Title;
const heading = document.createElement("h1");
heading.innerHTML = movieName;
movieDiv.appendChild(heading);
const movieImg = document.createElement("img");
movieImg.src = movie.Poster;
movieDiv.appendChild(movieImg);
const movieYear = document.createElement("year");
movieYear.innerHTML = movie.Year;
movieDiv.appendChild(movieYear);
}
I've tried using multiple variables and changing the inputs, but nothing seems to be working. When I try to use multiple array values, no results show up at all.
Any help would be appreciated

How to display all data

Hello I need help with showing all of a certain piece of data. my code is below
const [server, setServer] = useState()
const getServer = useCallback(async () => {
// const id = what do I do here??
const unsubscribe = firebase.db.collection("servers").doc('S7FlCYEvxIVDs7MRymnK').onSnapshot(snapshot => {
setServer(snapshot.data())
})
return unsubscribe
},[props.server])
useEffect(() => {
getServer()
}, [props])
console.log(server)
you can see I want to replace the hard coded doc info with an id variable, so in my project I can show multiple servers instead of a hard coded one I choose.

I'm getting the first response an empty list

I'm getting data from API like this:
const [software, setSoftware] = useState([]);
const id = match.params.id;
useEffect(() => {
fetch(`http://127.0.0.1:8000/api/software/${id}/`)
.then(response => response.json())
.then(data => {
setSoftware(data)
})
}, [id]);
First response is an empty list, but the next response is my list from API. I tried to use useEffect because setSoftwares is asynchronous, but it didn't help.
So how can I get only my list?
I think you are sending incorrect id for the first time, try to console.log(id) it and check-in the console if id is valid or not.

How to fetch data after clicking button and limit number of fetch-es

I would like to use SWAPI (https://swapi.co/) to fetch data, I have created below code, but I am concern that I use too much fetch- that the architecture is wrong.
The plan is: 1st fetch base data (create buttons from them) then click the button and fetch data from another URL and display them (when links are shown, also change them to buttons)
I have created buttons and fetch data (for now console.log them)
//get the base list of attributes
let mainContent = document.getElementById('mainContent'); // div with id=mainContent
let mainList = new Map();
let mainUrl = fetch('https://swapi.co/api/'); //base URL
mainUrl
.then(response => response.json())
.then(list => {
for (let main in list) {
mainList.set(main, list[main]);
}
mainList.forEach((value, key) => {
createButton(value, key);
});
})
.catch(err => console.error('Caught error: ', err));
let createButton = (value, key) => {
let button = document.createElement('button');
button.setAttribute('name', key);
button.setAttribute('value', value);
button.innerHTML = key;
button.addEventListener('click', e => {
console.log(e.target.value);
return fetch(e.target.value)
.then(response => response.json())
.then(resp => {
console.log(resp.results);
});
});
mainContent.appendChild(button);
};
I expect to list people etc. from clicked URLs but i would expect to use less fetch

Getting a specific object/item by id in Firebase

I am currently building a small web app with Firebase and React, but I am having trouble fetching for specific items in the Firebase from the React client-side.
That being said, I'm used to javascript, where a simple fetch might look something like:
const url = 'www.example.com/api/'
const id = '123'
fetch(url + id) <---specific
.then(res => res.json())
.then(result => this.setState({results: result})
.catch(err => console.log(err))
However, I haven't been able to find any documentation on something that looks similar with firebase.
A more specific issue below:
class StoryItem extends Component {
constructor(props) {
super(props);
this.state = {
story: this.props.location.myCustomProps
};
}
componentDidMount() {
//this should do a fetch request based on the
//params id to get the specific item in the firebase
//right now it is being passed as prop which is unreliable because when page refresh state is reset
//user should be able to access content
//without having to go to previous page
console.log(this.state.story)
}
One way I've tried to get the specific object from the firebase is this:
componentDidMount(props) {
const ref = firebase.database().ref("items");
ref.on("value", snapshot => {
let storiesObj = snapshot.val();
storiesObj
.child(this.props.match.params.id)
.then(() => ref.once("value"))
.then(snapshot => snapshot.val())
.catch(error => ({
errorCode: error.code,
errorMessage: error.message
}));
});
}
In this case, the error is
Any help would be appreciated, also, if anyone knows of any good documentation on firebase, feel free to send me a link.
Thank you
The trick is, you don't have to get the value of all items first, as you do.
You should locate the items ref, then lookup a child that you want and get the value of that child with .on or .once.
Something like that, based on your example code:
componentDidMount() {
firebase.database().ref("items");
.child(this.props.match.params.id)
.once("value")
.then(snapshot => snapshot.val())
.catch(error => ({
errorCode: error.code,
errorMessage: error.message
}));
}
For better understanding, let's take a look at the original code and try to figure out why it errors out:
componentDidMount(props) {
// ⬇️ this ref points to ALL items
const ref = firebase.database().ref("items");
// ⬇️ here we're asking for the value stored under the above ref
ref.on("value", snapshot => {
let storiesObj = snapshot.val();
/* so firebase gives us what we ask for, storiesObj
* is probably a huge js object with all the items inside.
* And since it's just a regular js object,
* it does not have a `child` method on it, thus calling .child errors out.
*/
storiesObj
.child(this.props.match.params.id)
.then(() => ref.once("value"))
.then(snapshot => snapshot.val())
.catch(error => ({
errorCode: error.code,
errorMessage: error.message
}));
});
}

Categories

Resources