I already check again on this code, but still couldn't figure it out why it won't work. So that I manage to make this web app using GitHub API.
but when I tried to search some data by their name, it turns out 'undefined' for everything that I was trying to find, like name, image, bio and etc.
My html code:
<html>
<head>
<title>Github Profile!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id="form">
<input type="text"
id="search"
placeholder="Search a User Here" />
</form>
<main id="main"></main>
<script src="script.js" defer></script>
</body>
</html>
Javascript:
const APIURL = 'https://api.github.com/users';
const main = document.getElementById('main');
const form = document.getElementById('form');
const search = document.getElementById('search');
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
function createUserCard(user) {
const cardHTML = `
<div class="card">
<div>
<img src="${user.avatar_url}"
alt="${user.name}" />
</div>
<div>
<h2>${user.name}</h2>
<p>${user.bio}</p>
<ul>
<li>${user.followers}</li>
<li>${user.following}</li>
<li>${user.public_repos}</li>
</ul>
</div>
</div>
`;
main.innerHTML = cardHTML;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const user = search.value;
if (user) {
getUser(user);
search.value = "";
}
});
I don't know what actually went wrong here.
Looks like you were just using the wrong URL.
const APIURL = 'https://api.github.com/users'; // no end slash
async function getUser(user) {
const resp = await fetch(APIURL + user );
so what you're doing here is calling the URL
https://api.github.com/usersusername
so you just need to add a slash in the APIURL variable.
const APIURL = 'https://api.github.com/users/';
const main = document.getElementById('main');
const form = document.getElementById('form');
const search = document.getElementById('search');
async function getUser(user) {
const resp = await fetch(APIURL + user);
console.log(resp)
const respData = await resp.json();
console.log(respData)
createUserCard(respData);
}
function createUserCard(user) {
const cardHTML = `
<div class="card">
<div>
<img src="${user.avatar_url}"
alt="${user.name}" />
</div>
<div>
<h2>${user.name}</h2>
<p>${user.bio}</p>
<ul>
<li>${user.followers}</li>
<li>${user.following}</li>
<li>${user.public_repos}</li>
</ul>
</div>
</div>
`;
main.innerHTML = cardHTML;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const user = search.value;
if (user) {
getUser(user);
search.value = "";
}
});
<html>
<head>
<title>Github Profile!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id="form">
<input type="text" id="search" placeholder="Search a User Here" />
</form>
<main id="main"></main>
<script src="script.js" defer></script>
</body>
</html>
Just add / after the users.
Your Code:
const APIURL = 'https://api.github.com/users';
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
Working Code:
const APIURL = 'https://api.github.com/users/';
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
This will get you the correct URL for the user
https://api.github.com/users/thesumitshrestha
Related
Hello there I am struggling to find the solution of this 'bug'. I am not even sure why its happening? Using Giphy API the goal is to upload gif then save the id from response to the localStorage.The initial upload seem to work fine, however each next upload does a multiple fetches and adds in the localStorage more than one id for each gif. Will really appreciate any advice. Thanks!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form>
<input type="file" />
<input type="submit" />
</form>
<div class="tree"></div>
<script src="./fetch-api.js"></script>
</body>
</html>
JavaScript:
const form = document.querySelector('form');
const inputFlie = document.querySelector('input');
const preview = document.querySelector('.tree');
const apiKey = 'yourapikeyhere'
form.addEventListener('change', () => {
const uploadFile = new FormData();
uploadFile.append('file', inputFlie.files[0]);
const heads = {
method: 'POST',
api_key: apiKey ,
body: uploadFile,
};
form.addEventListener('submit', async (event) => {
event.preventDefault();
try {
const send = await fetch(
`https://upload.giphy.com/v1/gifs?api_key=${apiKey}`,
heads
);
const feedback = await send.json();
if (feedback.meta.status === 200) {
form.reset();
uploadID = feedback.data.id;
}
if (localStorage.getItem('uploaded') === null) {
//if we don't create an empty array
uploadedGifs = [];
uploadedGifs.push(uploadID);
localStorage.setItem('uploaded', JSON.stringify(uploadedGifs));
} else {
const currentItems = JSON.parse(localStorage.getItem('uploaded'));
currentItems.push(uploadID);
localStorage.setItem('uploaded', JSON.stringify(currentItems));
}
console.log(feedback);
} catch (error) {
console.log(error);
statusMesage.textContent = 'Something went wrong!';
}
});
});
separate event listeners, so as not to create a new one every time the form has been changed.
const form = document.querySelector('form');
const inputFlie = document.querySelector('input');
const preview = document.querySelector('.tree');
const apiKey = 'yourapikeyhere'
const heads = {
method: 'POST',
api_key: apiKey,
body: null,
};
form.addEventListener('change', () => {
const uploadFile = new FormData();
uploadFile.append('file', inputFlie.files[0]);
heads.body = uploadFile;
});
form.addEventListener('submit', async (event) => {
event.preventDefault();
try {
const send = await fetch(
`https://upload.giphy.com/v1/gifs?api_key=${apiKey}`,
heads
);
const feedback = await send.json();
if (feedback.meta.status === 200) {
form.reset();
uploadID = feedback.data.id;
}
if (localStorage.getItem('uploaded') === null) {
//if we don't create an empty array
uploadedGifs = [];
uploadedGifs.push(uploadID);
localStorage.setItem('uploaded', JSON.stringify(uploadedGifs));
} else {
const currentItems = JSON.parse(localStorage.getItem('uploaded'));
currentItems.push(uploadID);
localStorage.setItem('uploaded', JSON.stringify(currentItems));
}
console.log(feedback);
} catch (error) {
console.log(error);
statusMesage.textContent = 'Something went wrong!';
}
});
I am training on the Hacker News API project and I wanted to do it my way, I fetched the API with the following urls and I put a toggle_button function but when I try to put the variable data in this function nothing is displayed I do not know what is the problem can someone guide me?
Here's my HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>ClonerNews</title>
</head>
<body>
<h2>Welcome To <span>ClonerNews</span> !</h2>
<div id="main">
<button id="liveData" class="category" onclick="toggleButton('liveData');">Live Data</button>
<button id="topstories" class="category" onclick="toggleButton('topstories');">Top Stories</button>
<button id="stories" class="category" onclick="toggleButton('stories');">Stories</button>
<button id="jobs" class="category" onclick="toggleButton('jobs');">Jobs</button>
<button id="polls" class="category" onclick="toggleButton('polls');">Polls</button>
</div>
<div id="result"></div>
<span id="span_txt" style="color: aliceblue;"></span>
</body>
<script src="script.js"></script>
</html>
And here's my script.js
//url of news api
var topStoriesUrl = "https://hacker-news.firebaseio.com/v0/topstories.json";
//url of particular news item
var newItemUrl = "https://hacker-news.firebaseio.com/v0/item/";
let result = document.getElementById("result"); seront affichées.
//fetch data
const fetchData = (url) => {
return new Promise((resolve, reject) => {
fetch(url)
.then((res) => res.json())
.then((data) => resolve(data))
.catch((err) => reject(err));
});
};
//show data
const showData = async () => {
var data = await fetchData(topStoriesUrl);
console.log(data);
data.map(async (d) => {
let newsData = await fetchData(`${newItemUrl}${d}.
json`);
console.log(newsData);
});
};
showData();
const liveData = getElementById("liveData");
const stories = getElementById("stories");
const jobs = getElementById("jobs");
const polls = getElementById("polls");
function toggleButton() {
var span = document.getElementById("span_txt");
if(span.innerHTML != "") {
span.innerHTML = "";
} else {
span.innerHTML = data
}
}
GET method with the list of cars:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/cars', (req, res) => {
res.status(200).json([{
name : 'a',
color : 'red'
},{
name : 'b',
color : 'blue'
}])
})
module.exports = app
I'm trying to load the list into my html page=>
When clicking on the button with the load id, the list ofcars on the server is requested; cars with red color are loaded into the table withmain id with a tr
for each car.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>A simple app</title>
<script>
async function load(){
try{
let url ='http://localhost:8080/cars'
let response = await fetch(url)
let data = await response.json()
let table = document.getElementById('main')
table.innerHTML = ''
for (let e of data){
let rowContent = `
<tr>
<td>
${e.name}
</td>
<td>
${e.color}
</td>
</tr>`
let row = document.createElement('tr')
row.innerHTML = rowContent
//row.dataset.id = e.id
table.append(row)
}
catch(err){
console.warn(err)
}
}
}
</script>
</head>
<body>
A simple app
<table id=main></table>
<input type="button" value="add" onClick={load()} id="load"/>
</body>
</html>
There's few reason why you can't do it, it's because cors, catch block and port.
Maybe you can try this html below:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>A simple app</title>
<script>
async function load(){
try {
let url ='http://localhost:3000/cars';
let response = await fetch(url);
let data = await response.json()
let table = document.getElementById('main');
table.innerHTML = '';
for (let e of data){
let rowContent = `
<tr>
<td>${e.name}</td>
<td>${e.color}</td>
</tr>`;
let row = document.createElement('tr')
row.innerHTML = rowContent;
table.append(row);
}
} catch(ex) {
console.log(ex);
}
}
</script>
</head>
<body>
A simple app
<table id=main></table>
<input type="button" value="add" onClick={load()} id="load"/>
</body>
</html>
And now, in your server, you can change with this simple server:
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors( { origin: '*'}));
app.get('/cars', (req, res) => {
res.status(200).json([{
name : 'a',
color : 'red'
},{
name : 'b',
color : 'blue'
}])
});
app.listen(3000, () => {
console.log('Server is up');
});
I hope it can help you.
Could anyone explain to me why I cannot update my input value after clicking my submit button? My goal is to write a number, click the submit button and find the Pokémon with that number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div class="pokemon"></div>
<button id="btn" onclick="testFunc(inputValue)">SUBMIT</button>
<input type="text" value="" id="myInput">
<script>
const btn = document.getElementById("btn");
const input = document.getElementById("myInput");
let inputValue = input.value;
const testFunc = function(a) {
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: a,
}
const { url, type, id } = apiData
const apiUrl = `${url}${type}/${id}`
fetch(apiUrl)
.then((data) => {
if (data.ok) {
return data.json()
}
throw new Error('Response not ok.');
})
.then(pokemon => generateHtml(pokemon))
.catch(error => console.error('Error:', error))
const generateHtml = (data) => {
console.log(data)
const html = `
<div class="name">${data.name}</div>
<img src=${data.sprites.front_default}>
<div class="details">
<span>Height: ${data.height}</span>
<span>Weight: ${data.weight}</span>
</div>
`
const pokemonDiv = document.querySelector('.pokemon')
pokemonDiv.innerHTML = html
}
}
</script>
</body>
</html>
I will be grateful for any advice.
Best regards
You need to move the inputValue retrieval inside the testFunc function.
const testFunc = function() {
let inputValue = input.value;
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: inputValue,
}
The button's onclick only knows about itself, it cannot reference input.
const btn = document.getElementById("btn");
const input = document.getElementById("myInput");
const testFunc = function() {
let inputValue = input.value;
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: inputValue,
}
const { url, type, id } = apiData
const apiUrl = `${url}${type}/${id}`
fetch(apiUrl)
.then((data) => {
if (data.ok) {
return data.json()
}
throw new Error('Response not ok.');
})
.then(pokemon => generateHtml(pokemon))
.catch(error => console.error('Error:', error))
const generateHtml = (data) => {
//console.log(data) <-- Slows down the result
const html = `
<div class="name">${data.name}</div>
<img src=${data.sprites.front_default}>
<div class="details">
<span>Height: ${data.height}</span>
<span>Weight: ${data.weight}</span>
</div>
`
const pokemonDiv = document.querySelector('.pokemon')
pokemonDiv.innerHTML = html
}
}
<div class="pokemon"></div>
<button id="btn" onclick="testFunc()">SUBMIT</button>
<input type="text" value="25" id="myInput"> <!-- Default to Pikachu -->
I have written code in javascript and html. The goal of that was to get a user to log in into youtube and once they do, they will see some feed. Now i want to use this code into a reactjs project. the question is how can i do this. I am having trouble doing that. the code below is the html and java script code i wrote. Now the code at the bottom is what i tried to do in reactjs.
// Options
const CLIENT_ID = '530254027383-djo7723li5ju3c6t4e2taacvj5idbp50.apps.googleusercontent.com';
const DISCOVERY_DOCS = [
'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest'
];
const SCOPES = 'https://www.googleapis.com/auth/youtube.readonly';
const authorizeButton = document.getElementById('authorize-button');
const signoutButton = document.getElementById('signout-button');
const content = document.getElementById('content');
const channelForm = document.getElementById('channel-form');
const channelInput = document.getElementById('channel-input');
const videoContainer = document.getElementById('video-container');
const defaultChannel = 'techguyweb';
// Form submit and change channel
channelForm.addEventListener('submit', e => {
e.preventDefault();
const channel = channelInput.value;
getChannel(channel);
});
// Load auth2 library
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
// Init API client library and set up sign in listeners
function initClient() {
gapi.client
.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
})
.then(() => {
// Listen for sign in state changes
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle initial sign in state
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
// Update UI sign in state changes
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
content.style.display = 'block';
videoContainer.style.display = 'block';
getChannel(defaultChannel);
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
content.style.display = 'none';
videoContainer.style.display = 'none';
}
}
// Handle login
function handleAuthClick() {
gapi.auth2.getAuthInstance().signIn();
}
// Handle logout
function handleSignoutClick() {
gapi.auth2.getAuthInstance().signOut();
}
// Display channel data
function showChannelData(data) {
const channelData = document.getElementById('channel-data');
channelData.innerHTML = data;
}
// Get channel from API
function getChannel(channel) {
gapi.client.youtube.channels
.list({
part: 'snippet,contentDetails,statistics',
forUsername: channel
})
.then(response => {
console.log(response);
const channel = response.result.items[0];
const output = `
<ul class="collection">
<li class="collection-item">Title: ${channel.snippet.title}</li>
<li class="collection-item">ID: ${channel.id}</li>
<li class="collection-item">Subscribers: ${numberWithCommas(
channel.statistics.subscriberCount
)}</li>
<li class="collection-item">Views: ${numberWithCommas(
channel.statistics.viewCount
)}</li>
<li class="collection-item">Videos: ${numberWithCommas(
channel.statistics.videoCount
)}</li>
</ul>
<p>${channel.snippet.description}</p>
<hr>
<a class="btn grey darken-2" target="_blank" href="https://youtube.com/${
channel.snippet.customUrl
}">Visit Channel</a>
`;
showChannelData(output);
const playlistId = channel.contentDetails.relatedPlaylists.uploads;
requestVideoPlaylist(playlistId);
})
.catch(err => alert('No Channel By That Name'));
}
// Add commas to number
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
function requestVideoPlaylist(playlistId) {
const requestOptions = {
playlistId: playlistId,
part: 'snippet',
maxResults: 10
};
const request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(response => {
console.log(response);
const playListItems = response.result.items;
if (playListItems) {
let output = '<br><h4 class="center-align">Latest Videos</h4>';
// Loop through videos and append output
playListItems.forEach(item => {
const videoId = item.snippet.resourceId.videoId;
output += `
<div class="col s3">
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
`;
});
// Output videos
videoContainer.innerHTML = output;
} else {
videoContainer.innerHTML = 'No Uploaded Videos';
}
});
}
now the code above was the javascript and now the code below is the html I used.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<style>
#content,
#authorize-button,
#signout-button {
display: none
}
</style>
<title>YouTube Channel Data</title>
</head>
<body>
<nav class="black">
<div class="nav-wrapper">
<div class="container">
YouTube Channel Data
</div>
</div>
</nav>
<br>
<section>
<div class="container">
<p>Log In With Google</p>
<button class="btn red" id="authorize-button">Log In</button>
<button class="btn red" id="signout-button">Log Out</button>
<br>
<div id="content">
<div class="row">
<div class="col s6">
<form id="channel-form">
<div class="input-field col s6">
<input type="text" placeholder="Enter Channel Name" id="channel-input">
<input type="submit" value="Get Channel Data" class="btn grey">
</div>
</form>
</div>
<div id="channel-data" class="col s6"></div>
</div>
<div class="row" id="video-container"></div>
</div>
</div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="main.js"></script>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
the code below is the code i tried to do in reactjs ,but it is not working . Any idea on how i can get it to work or if it is even possible?
import React, { Component } from 'react'
import YouTube from 'react-youtube';
/* global gapi */
const CLIENT_ID = '530254027383-djo7723li5ju3c6t4e2taacvj5idbp50.apps.googleusercontent.com';
const DISCOVERY_DOCS = [
'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest'
];
const SCOPES = 'https://www.googleapis.com/auth/youtube.readonly';
const authorizeButton = document.getElementById('authorize-button');
const signoutButton = document.getElementById('signout-button');
const content = document.getElementById('content');
const channelForm = document.getElementById('channel-form');
const channelInput = document.getElementById('channel-input');
const videoContainer = document.getElementById('video-container');
const defaultChannel = 'techguyweb';
export default class youtube extends Component {
// Form submit and change channel
channelForm.addEventListener('submit', e => {
e.preventDefault();
const channel = channelInput.value;
getChannel(channel);
});
// Load auth2 library
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
// Init API client library and set up sign in listeners
function initClient() {
gapi.client
.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
})
.then(() => {
// Listen for sign in state changes
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle initial sign in state
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
// Update UI sign in state changes
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
content.style.display = 'block';
videoContainer.style.display = 'block';
getChannel(defaultChannel);
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
content.style.display = 'none';
videoContainer.style.display = 'none';
}
}
// Handle login
function handleAuthClick() {
gapi.auth2.getAuthInstance().signIn();
}
// Handle logout
function handleSignoutClick() {
gapi.auth2.getAuthInstance().signOut();
}
// Display channel data
function showChannelData(data) {
const channelData = document.getElementById('channel-data');
channelData.innerHTML = data;
}
// Get channel from API
function getChannel(channel) {
gapi.client.youtube.channels
.list({
part: 'snippet,contentDetails,statistics',
forUsername: channel
})
.then(response => {
console.log(response);
const channel = response.result.items[0];
const output = `
<ul class="collection">
<li class="collection-item">Title: ${channel.snippet.title}</li>
<li class="collection-item">ID: ${channel.id}</li>
<li class="collection-item">Subscribers: ${numberWithCommas(
channel.statistics.subscriberCount
)}</li>
<li class="collection-item">Views: ${numberWithCommas(
channel.statistics.viewCount
)}</li>
<li class="collection-item">Videos: ${numberWithCommas(
channel.statistics.videoCount
)}</li>
</ul>
<p>${channel.snippet.description}</p>
<hr>
<a class="btn grey darken-2" target="_blank" href="https://youtube.com/${
channel.snippet.customUrl
}">Visit Channel</a>
`;
showChannelData(output);
const playlistId = channel.contentDetails.relatedPlaylists.uploads;
requestVideoPlaylist(playlistId);
})
.catch(err => alert('No Channel By That Name'));
}
// Add commas to number
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
function requestVideoPlaylist(playlistId) {
const requestOptions = {
playlistId: playlistId,
part: 'snippet',
maxResults: 10
};
const request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(response => {
console.log(response);
const playListItems = response.result.items;
if (playListItems) {
let output = '<br><h4 class="center-align">Latest Videos</h4>';
// Loop through videos and append output
playListItems.forEach(item => {
const videoId = item.snippet.resourceId.videoId;
output += `
<div class="col s3">
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
`;
});
// Output videos
videoContainer.innerHTML = output;
} else {
videoContainer.innerHTML = 'No Uploaded Videos';
}
});