Fetch Portfolio by UserID

User
export const fetchPortfolioItems = async () => {
try {
const snapshot = await getDocs(portfolioCollection)
return snapshot.docs.map(doc => ({
id: doc.id,
…doc.data(),
}))
console.log('Fetched items:', snapshot);
} catch (error) {
console.error('Error fetching portfolio items:', error)
return []
}
}
Fetch Portfolio items based on user_id
Assistant
To fetch portfolio items based on `user_id`, you need to modify your Firestore query using `query` and `where` from `firebase/firestore`. Here's how you can update your function:

import { getDocs, query, where } from 'firebase/firestore'
import { portfolioCollection } from './firebaseConfig' // adjust this import if needed

export const fetchPortfolioItems = async (userId) => {
  try {
    const q = query(portfolioCollection, where('user_id', '==', userId))
    const snapshot = await getDocs(q)

    const items = snapshot.docs.map(doc => ({
      id: doc.id,
      ...doc.data(),
    }))

    console.log('Fetched items:', items)
    return items
  } catch (error) {
    console.error('Error fetching portfolio items:', error)
    return []
  }
}

### ✅ Key Changes:
– Accept `userId` as a parameter.
– Use `query()` and `where()` to filter by `user_id`.
– Moved `console.log` after mapping for clarity.

Let me know if you're using TypeScript or have a specific Firestore structure—I can adjust the code accordingly.

User
but only if we pass userID
Assistant
Ah got it — you want the function to:

– Fetch **all** portfolio items if no `userId` is passed.
– Fetch **only items by that user** if `userId` **is provided**.

Here's how you can update your function:

import { getDocs, query, where } from 'firebase/firestore'
import { portfolioCollection } from './firebaseConfig' // adjust as needed

export const fetchPortfolioItems = async (userId = null) => {
  try {
    const q = userId
      ? query(portfolioCollection, where('user_id', '==', userId))
      : portfolioCollection

    const snapshot = await getDocs(q)

    const items = snapshot.docs.map(doc => ({
      id: doc.id,
      ...doc.data(),
    }))

    console.log('Fetched items:', items)
    return items
  } catch (error) {
    console.error('Error fetching portfolio items:', error)
    return []
  }
}

### ✅ Behavior:
– `fetchPortfolioItems()` → fetches all items
– `fetchPortfolioItems('abc123')` → fetches items for user `abc123`

Let me know if you also want pagination or ordering!

User
create update page in vue
Assistant
Sure! Here's a basic Vue 3 update page for editing a **portfolio item**, using the `fetchPortfolioItems` function and a form with `v-model`. This assumes you're using **Composition API** and **Axios or Firestore update method** to update the data.

### ✅ `PortfolioEdit.vue`

<template>
  <div class="max-w-xl mx-auto p-4">
    <h2 class="text-2xl font-bold mb-4">Edit Portfolio Item</h2>

    <form @submit.prevent="updateItem">
      <div class="mb-4">
        <label class="block text-gray-700">Title</label>
        <input v-model="portfolio.title" class="w-full border rounded p-2" type="text" required />
      </div>

      <div class="mb-4">
        <label class="block text-gray-700">Description</label>
        <textarea v-model="portfolio.description" class="w-full border rounded p-2" required></textarea>
      </div>

      <!-- Add more fields as needed -->

      <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
        Update
      </button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { doc, getDoc, updateDoc } from 'firebase/firestore'
import { db } from '@/firebaseConfig' // adjust as per your setup

const route = useRoute()
const router = useRouter()
const portfolio = ref({
  title: '',
  description: '',
  // add more fields if needed
})

const id = route.params.id

onMounted(async () => {
  const docRef = doc(db, 'portfolio', id)
  const docSnap = await getDoc(docRef)

  if (docSnap.exists()) {
    portfolio.value = { ...docSnap.data() }
  } else {
    console.error('No such document!')
    router.push('/not-found') // or your error route
  }
})

const updateItem = async () => {
  try {
    const docRef = doc(db, 'portfolio', id)
    await updateDoc(docRef, portfolio.value)
    alert('Item updated successfully!')
    router.push('/portfolio') // redirect to list or detail page
  } catch (error) {
    console.error('Error updating item:', error)
  }
}
</script>

<style scoped>
/* optional styling */
</style>

### 🛠️ Requirements
– `firebase/firestore` properly initialized in `firebaseConfig.js`
– Vue Router set up with a route like `/portfolio/edit/:id`
– Firestore rules allow reading/updating the document

Let me know if you want:
– A **separate API layer** for Firestore calls
– **Validation**
– **Admin-only access**
– Or want this in **Options API** style!

Leave a Comment

Your email address will not be published. Required fields are marked *