aayush192 / news-99

0 stars 0 forks source link

issue #1

Open sandeshkhadka283 opened 2 months ago

sandeshkhadka283 commented 2 months ago

// Define constants and variables const apiKey = process.env.API_KEY; // Ensure this environment variable is set in your Vercel settings const baseUrl = 'https://newsapi.org/v2/everything'; let searchQuery = 'health';

// Function to fetch and display articles async function fetchAndDisplayArticles(query) { const url = ${baseUrl}?q=${encodeURIComponent(query)}&apiKey=${apiKey};

try {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    const articles = data.articles;

    if (articles.length > 0) {
        renderArticles(articles);
    } else {
        displayNoResults();
    }
} catch (error) {
    console.error('Fetch error:', error);
    displayError(error.message);
}

}

// Function to render articles to the DOM function renderArticles(articles) { const container = document.querySelector('.boxes'); container.innerHTML = articles .filter(article => article.content !== "[Removed]" && article.urlToImage) .map(article => `

${article.title}
${formatAuthor(article)}
${article.title}
${truncateText(article.content, 60)}..
${truncateText(article.description, 200)}..
    `).join('');

}

// Helper function to format author information function formatAuthor(article) { return ${article.source.name}<br>${new Date(article.publishedAt).toLocaleDateString()}; }

// Helper function to truncate text function truncateText(text, length) { return text ? text.slice(0, length) : ''; }

// Function to handle displaying when there are no results function displayNoResults() { document.querySelector('.boxes').innerHTML = '

No articles found.

'; }

// Function to handle displaying errors function displayError(message) { document.querySelector('.boxes').innerHTML = <p>Error: ${message}</p>; }

// Event listeners for search functionality document.querySelector('.search-button').addEventListener('click', () => { searchQuery = document.querySelector('.search-bar').value; fetchAndDisplayArticles(searchQuery); });

document.querySelectorAll('.option').forEach(button => { button.addEventListener('click', (event) => { searchQuery = event.target.dataset.nameSearch; fetchAndDisplayArticles(searchQuery); }); });

// Initial fetch fetchAndDisplayArticles(searchQuery);