I am trying to build a form with comments. Comments are loaded using API and also new comments are posted to the API if submitted using two input fields and a submit button. The process is working, however the date of the comments writes "invalid date" when posted, but after refreshing the page the date is correct. My question is if anyone knows what could be the issue here? So to post a new comment, you have to input a name and the comment, date should be generated automatically. Thank you everyone. This is my js code below
axios
.get(showUrl + "?api_key=" + apiKey)
.then((response) => {
commentArray = response.data;
commentArray.forEach((commentContainer) => {
displayComment(commentContainer);
console.log("something")
})
})
.catch(error => {
console.log(error);
})
let commentArray = [];
function displayComment(arr) {
let commentContainer = document.createElement("div");
commentContainer.classList.add("comments__posted-container");
let roundLogo = document.createElement("div");
roundLogo.classList.add("comments__grey-round-logo");
let addedComments = document.createElement("div");
addedComments.classList.add("comments__added");
let nameDate = document.createElement("div");
nameDate.classList.add("name-date");
let nameUser = document.createElement("h4");
nameUser.innerText = arr.name;
let dateUser = document.createElement("p");
dateUser.classList.add("comments__added-date");
dateUser.innerText = new Date(Number(arr.timestamp)).toLocaleDateString();
let commentUser = document.createElement("p");
commentUser.innerText = arr.comment;
inputComment.appendChild(commentContainer);
commentContainer.appendChild(roundLogo);
commentContainer.appendChild(addedComments);
addedComments.appendChild(nameDate);
addedComments.appendChild(commentUser);
nameDate.appendChild(nameUser);
nameDate.appendChild(dateUser);
}
commentArray.forEach((commentContainer) => {
displayComment(commentContainer);
})
console.log(commentArray)
let formComment = document.querySelector(".comments__form")
let today = new Date();
formComment.addEventListener('submit', (event) => {
event.preventDefault();
let nameInput = event.target.name.value;
let commentInput = event.target.comment.value;
axios
.post(showUrl + "?api_key=" + apiKey, {
name: nameInput,
comment: commentInput,
// timestamp: today.toLocaleDateString(),
})
.then((response) => {
axios
.get(showUrl + "?api_key=" + apiKey)
.then((response) => {
let comments = response.data;
comments.innerText = "";
commentContainer(comments);
})
})
.catch((error) => {
});
if (nameInput && commentInput) {
commentArray.unshift({
name: nameInput,
comment: commentInput,
date: today.toLocaleDateString(),
// today: `${Date.now()}`
})
displayComment(commentArray[0])
}
formComment.reset()
})
Related
I can't figure out where to put the curly brackets or parenthesis to make it work correctly. At first I thought the server was down or something but then I managed to console log the data. I kept uninstalling and reinstalling this visual studio code extension called "Bracket Colorizer" to try and solve the but I am all out of juice.
document.addEventListener('DOMContentLoaded', () => {
const title = document.createElement('h1');
title.innerText = 'Online Chatroom';
document.querySelector('body').appendChild(title);
// make AJAX call here....
fetch('https://curriculum-api.codesmith.io/messages')
.then(data => data.json())
.then(data => {
const main = document.querySelector('main')
for (let i = 0; i < data.length; i++) {
writeHTML(data[i], main)
// console.log(data);
});
};
};
Here is the rest of the code me and my tutor from wyzant worked on together if it helps.
document.querySelector('form').addEventListener('submit', sendMessage)
function writeHTML(message, htmlNode) {
let messageContainer = document.createElement('div')
let messageText = document.createElement('p')
messageText.innerHTML = message.message
messageContainer.appendChild(messageText)
let messageTime = document.createElement('span')
messageTime.classList.add('time')
messageTime.innerText = message.created_at
messageContainer.appendChild(messageTime)
linebreak = document.createElement("br");
messageContainer.appendChild(linebreak);
// // document.innerHTML(<br>)
let createdBy = document.createElement('span')
createdBy.classList.add('message_sender')
createdBy.innerText = message.created_by
messageContainer.appendChild(createdBy)
htmlNode.appendChild(messageContainer)
}
function sendMessage(event) {
event.preventDefault()
let newMessage = document.querySelector('textarea').value
let data = {
message: newMessage,
//figure out how to add another text box and insert that data here
created_by: "Matthew",
created_at: Date.now()
}
fetch('https://curriculum-api.codesmith.io/messages', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response){
return response.json()
})
.then(function(response){
const main = document.querySelector('main')
writeHTML(response[0], main)
})
.catch(function(error){
console.error(error)
})
};
This parenthesis is misplaced:
// console.log(data);
}); <-- this one
};
// console.log(data);
}
}); <-- should be here
You had two parenthesis misplaced, you can check with the code below:
document.addEventListener('DOMContentLoaded', () => {
const title = document.createElement('h1');
title.innerText = 'Online Chatroom';
document.querySelector('body').appendChild(title);
// make AJAX call here....
fetch('https://curriculum-api.codesmith.io/messages')
.then(data => data.json())
.then(data => {
const main = document.querySelector('main')
for (let i = 0; i < data.length; i++) {
writeHTML(data[i], main)
// console.log(data);
}
})
})
I am trying to autofill city and state fields based on zip code input using sepomex API (for Mexico), on a site in corvid by wix, which is based on javascript but I think there is something wrong in the line json.response[0]["ciudad"].
$w.onReady(function () {
$w("#input1").onInput(() =>{
let zipcode = $w("#input1").value;
$w("#input2").value = "";
$w("#input3").value = "";
if (zipcode.length === 5) {
let apiUrl = "";
apiUrl = "https://api-sepomex.hckdrk.mx/query/info_cp/";
fetch(apiUrl + zipcode, {method: 'get'})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
else{
return Promise.reject("fetch was not successful")
}
})
.then((json) => {
console.log(json);
let response = json.response;
$w("#input10").value = json.response[0]["ciudad"];
$w("#input11").value = json.response[0]["estado"];
$w("#text148").collapse();
})
.catch(() =>{
$w("#text148").expand()
})
}
})
I can't display any data
There is the output on API
[
{
"error": false,
"code_error": 0,
"error_message": null,
"response": {
"cp": "44110",
"asentamiento": "Vallarta Poniente",
"tipo_asentamiento": "Fraccionamiento",
"municipio": "Guadalajara",
"estado": "Jalisco",
"ciudad": "Guadalajara",
"pais": "México"
}
}
]
change code inside second promise to.
.then((json) => {
let response = json[0].response;
$w("#input10").value = response.ciudad;
$w("#input11").value = response.estado;
$w("#text148").collapse();
})
now it should work
Solved
.then((json) =>{
let response = json[0].response;
$w("#input11").value = json[0].response["ciudad"];
$w("#input10").value = json[0].response["estado"];
$w("#text148").collapse();
})
I'm working on a project for school, and i'm trying to use 2 parameters in a function, but they are from 2 different functions. I have no clue how i can use them both.
What i'm trying to do is to actually use the code in showCityInfo in the function handleClickImg, but in order to do that i need the data 'city'
which is passed onto showCityInfo from the function getCityInfo, where the data is collected from my php.
So in short, i want to use the data 'city' and 'marker(=e.currentTarget)' in a function to do the following code i put in bold
{
const init = () => {
let radiobutton = document.querySelectorAll('.radio_button');
radiobutton.forEach(r => {
r.addEventListener("change", changeOpacity);
let $heart = document.querySelectorAll('.sidebar > svg');
$heart.forEach(h => {
h.addEventListener('click', changeColor);
})
document.documentElement.classList.add('has-js');
const $input = document.querySelector(`.world_form`);
console.log($input);
if ($input) {
$input.addEventListener(`change`, handleChangeFilter);
}
});
$markers = document.querySelectorAll('.world_map > img');
console.log($markers);
$markers.forEach(marker => {
marker.addEventListener('click', handleClickImg);
})
}
const handleChangeFilter = e => {
const alignment = e.target.value;
console.log(alignment);
const path = window.location.href.split(`?`)[0];
const qs = `?alignment=${alignment}`;
getCityInfo(`${path}${qs}`);
};
const getCityInfo = async url => {
console.log(url);
const response = await fetch(url, {
headers: new Headers({
Accept: 'application/json'
})
});
const city = await response.json();
console.log(city);
window.history.pushState({}, ``, url);
showCityInfo(city);
};
const showCityInfo = city => { **
const $parent = document.querySelector(`.contact_wrapper`);
$parent.innerHTML = ``;
$parent.innerHTML += `<p class="contact_info"><span>email:</span> Carvee${city.name}#hotmail.com</p>
<p class="contact_info"><span>tel:</span> ${city.tel} 476 03 51 07</p>` **
};
const handleClickImg = e => {
marker = e.currentTarget;
console.log(marker);
if (marker.id == city.city_code) {
}
}
In case you only have to compare a city and a marker at a time, I think what you should do is declare two global variables outside of the functions to store the city and marker data and be able to access and compare them anywhere.
//...
let city, marker;
const getCityInfo = async url => {
console.log(url);
const response = await fetch(url, {
headers: new Headers({
Accept: 'application/json'
})
});
city = await response.json();
console.log(city);
window.history.pushState({}, ``, url);
showCityInfo();
};
const showCityInfo = () => {
const $parent = document.querySelector(`.contact_wrapper`);
$parent.innerHTML = ``;
$parent.innerHTML += `<p class="contact_info"><span>email:</span> Carvee${city.name}#hotmail.com</p><p class="contact_info"><span>tel:</span> ${city.tel} 476 03 51 07</p>`
};
const handleClickImg = e => {
marker = e.currentTarget;
console.log(marker);
if (marker.id == city.city_code) {
}
}
I'm trying to grab some data(title, last name, first name and also large photo of the user profile returned by the API.) from the API https://randomuser.me/api/, which seem to not be working.
const displayUserPhotoAndName = (data) => {
if(!data) return;
// add your code here
let {results} = data;
let [profile] = results;
document.querySelector('h2').textContent = profile.name.title +' '+ profile.name.last +' '+ profile.name.first;
document.querySelector('img').src = profile.picture.large;
displayExtraUserInfo(profile);
clearNotice();
};
const getAUserProfile = () => {
const api = 'https://randomuser.me/api/';
// make API call here
fetch(api)
.then((resp) => resp.json())
.then(data => {displayUserPhotoAndName()});
notify(`requesting profile data ...`);
};
const displayBirthdate = ({dob = 'dob'}) => {
document.querySelector('.details').textContent = dob.age;
}
const displayPhone = ({phone = 'phone', cell = 'cell'}) => {
document.querySelector('.details').textContent = phone + ', ' + cell;
}
const displayAddress = ({location = 'location'}) => {
document.querySelector('.details').textContent = location.street + ', ' + location.city + ', ' + location.state;
}
You are passing the data to the function.Do like below
const getAUserProfile = () => {
const api = 'https://randomuser.me/api/';
// make API call here
fetch(api)
.then((resp) => resp.json())
.then(data => {displayUserPhotoAndName(data)}); //this line is changed
notify(`requesting profile data ...`);
};
Here is the line that will get all the required properties
let {results:[{ name: { title , first , last } , picture:{ large } }]} = data;
Here is how you can do it and also handle bad data with default values. Also, do not forget to pass data to your function in the then callback:
const display = data => {
const { results: [{ name: { title, first, last } = {}, picture: { large } = {} }] = [] } = data || {};
console.log(title, first, last, large);
};
fetch('https://randomuser.me/api/').then(r => display(r.json()));
I'm trying to figure out a more efficient away to create the list items in the DOM.
At the moment the list is created as each API request is made.
I'm pushing each object into its own Array, I would like to create the list once all the data has loaded.
Additionally i'm using Webpack and Babel.
let streamApi = 'https://wind-bow.glitch.me/twitch-api/streams/';
let twitchUsers = ['ESL_SC2', 'OgamingSC2', 'freecodecamp', 'noobs2ninjas', 'comster404'];
let streamByUser = [];
window.onload = function() {
//Make a API request for each user and store in an array
twitchUsers.map((user) => {
fetch(streamApi + user, {method: 'GET'})
.then(response => response.json())
.then(json => {
streamByUser.push(json);
let uL = document.getElementById("user-list");
let listItem = document.createElement("li");
listItem.className = "list-group-item";
if (json.stream === null) {
listItem.innerHTML = "null";
} else {
listItem.innerHTML = json.stream.channel.display_name;
}
uL.appendChild(listItem);
});
});
};
UPDATE:
All is working!
Not tested but I hope it should work as expected.
const streamApi = "https://wind-bow.glitch.me/twitch-api/streams/";
const twitchUsers = [
"ESL_SC2",
"OgamingSC2",
"freecodecamp",
"noobs2ninjas",
"comster404"
];
const twitchUsersStreams = twitchUsers.map(user =>
fetch(streamApi + user, { method: "GET" }).then(res => res.json())
);
let streamByUser = [];
window.onload = function() {
Promise
.all(twitchUsersStreams)
.then(everythingArray => {
//do something with everythingArray after all the requests resolved
})
.catch(err => {
// As soon as any of the 'fetch' results in promise rejection
});
};
I would probably do something like this because I really like to decompose a task into small functions that reduce the need for inline comments and keep mutable state to a minimum.
const streamApi = 'https://wind-bow.glitch.me/twitch-api/streams/';
const twitchUsers = ['ESL_SC2', 'OgamingSC2', 'freecodecamp', 'noobs2ninjas', 'comster404'];
window.onload = async function () {
const list = document.getElementById("user-list");
const addToList = list.appendChild.bind(list);
const twitchStreams = await fetchUsers(twitchUsers);
twitchStreams.map(toListItem).forEach(addToList);
};
async function fetchUser(user) {
const response = await fetch(`${streamApi}${user}`, {method: 'GET'});
return response.json();
}
function fetchUsers(users) {
return Promise.all(users.map(fetchUser));
}
function toListItem(user) {
const listItem = document.createElement("li");
listItem.className = "list-group-item";
listItem.innerHTML = user.stream !== null
? user.stream.channel.display_name
: "null";
return listItem;
}