Not getting data through emit event. How do you communicate an array of selected IDs to the parent? - vuejs3

I am building this ecommerce site based on strapi and vue3/pinia.
My products come from ProductStore.js through this function:
async fillArchive() {
this.loading = true;
this.products = await fetch(
apiUrl +
"/api/products?fields=name,featured,description,price,slug&populate=image,category"
)
.then((res) => res.json())
.then((data) => (this.products = data.data))
.catch((err) => (error.value = console.log(err)));
this.loading = false;
},
I get my categories from CategoryStore.js:
async fill() {
this.loading = true;
this.categories = await fetch(apiUrl + "/api/categories?fields=name,slug")
.then((res) => res.json())
.then((data) => (this.categories = data.data))
.catch((err) => (error.value = err));
this.loading = false;
},
So the problem is that I am able to collect the selectedCategories in an array in the ProductFilters.vue child component, its also printed and shows up, but..
<script setup>
import { ref } from "vue";
import { useCategoryStore } from "#/stores/CategoryStore";
const categoryStore = useCategoryStore();
categoryStore.fill();
const checkedCategories = ref([]);
const emit = defineEmits(["changeCheck"]);
const changeCheck = function () {
emit("changeCheck", checkedCategories.value);
};
</script>
<template>
<div>
<label
v-for="category in categoryStore.categories"
:key="category.id"
class="text-sm flex flex-row items-center gap-1.5"
><input
type="checkbox"
:value="category.attributes.name"
v-model="checkedCategories"
#input="changeCheck"
/>{{ category.attributes.name }}</label
>
</div>
{{ checkedCategories }}
</template>
.. i am not getting the checkCategories array in the parent component, whereby I'd like to filter my rendered products. If a category is checked i'd like to render the related products, if all categories are checked render all, none checked also all.
In my parent component - ProductsView.vue - the emited data is not showing up, i'm always getting undefined.
<script setup>
import { computed } from "vue";
import { useProductStore } from "#/stores/ProductStore";
import IconDown from "../components/icons/IconDown.vue";
import IconUp from "../components/icons/IconUp.vue";
import ProductFilters from "../components/ProductFilters.vue";
import ProductArchiveCard from "../components/ProductArchiveCard.vue";
const imageLink = import.meta.env.VITE_STRAPI_URL;
const productStore = useProductStore();
function updateCategories(catName) {
let selected = [];
selected.push(catName);
return console.log(selected);
}
const filteredProducts = computed(() => {
// filter by catName or id and v-for filteredProducts
});
productStore.fillArchive();
</script>
<template>
<section class="px-2 flex flex-col xl:flex-row">
<div class="pt-24 xl:pt-36 xl:w-1/4 relative">
<!-- order by category -->
<ProductFilters #changeCheck="updateCategories(catName)" />
</div>
<div v-if="!productStore.loading">
<div
class="mx-auto grid grid-flow-row gap-10 md:gap-10 lg:gap-16 xl:gap-6 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4"
>
<ProductArchiveCard
class="mx-auto"
v-for="product in productStore.products"
:key="product.name"
:product="product"
:imageLink="imageLink"
/>
</div>
</div>
<div v-else class="flex justify-center py-16 min-h-screen">
<div class="spinner w-8 h-8"></div>
</div>
</section>
</template>
What am I doing wrong in the event handling? Can someone point it out? :) Thanks in advance folks!

Related

I am building an amazon clone, i am at the step to add stripe for payment, my build has worked as expected until now this is for a final please assist

my console is giving me the non specific error "Uncaught (in promise) AxiosError"
this is my checkout-session, in the terminal it seems to have a problem with the .map in the stripe session , ive verified the object format and made sure it was compliant with stripe standards, i am at a loss and hoping this may be a simple fix
import { useSession, useEffect } from 'next-auth/react'
import React from 'react'
import Header from '../components/Header'
import Image from 'next/image'
import { useSelector } from 'react-redux'
import { selectItems, selectTotal } from '../slices/basketSlice'
import CheckoutProduct from '../components/CheckoutProduct'
import Currency from 'react-currency-formatter'
import { link, loadStripe } from '#stripe/stripe-js'
import axios from 'axios'
const stripePromise = loadStripe(`${process.env.stripe_public_key}`);
function checkout() {
const { data: session } = useSession();
const total = useSelector(selectTotal);
const items = useSelector(selectItems);
const createCheckoutSession = async () => {
const stripe = await stripePromise
const checkoutSession = await axios.post('/api/create-checkout-session', {
items: items,
email: session.user.email
})
const result = await stripe.redirectToCheckout({
sessionId: checkoutSession.data.id
})
if (result.error) alert(result.error.message);
};
return (
<div className='bg-gray-100'>
<Header />
<main className='lg:flex max-w-screen-2xl mx-auto'>
{/* left */}
<div className='flex-grow m-5 shadow-sm'>
<Image
src='https://links.papareact.com/ikj'
width={1020}
height={250}
objectfit='contain'
/>
<div className='flex flex-col p-5 space-y-10 bg-white'>
<h1 className='text-3xl border-b pb-4'>{items.length === 0 ? 'Your Amazon Cart is Empty' : 'Shopping Cart'}</h1>
{items.map((item, i) => (
<CheckoutProduct
key={i}
id={item.id}
title={item.title}
rating={item.rating}
price={item.price}
description={item.description}
category={item.category}
image={item.image}
hasPrime={item.hasPrime}
/>
))}
</div>
</div>
{/* right */}
<div className='flex flex-col bg-white p-10 shadow-md'>
{items.length > 0 && (
<>
<h2 className='whitespace-nowrap'>Subtotal({items.length} items):
<span className='font-bold'>
<Currency quantity={total} currency="USD"/>
</span>
</h2>
<button
onClick={createCheckoutSession}
role={link}
disabled={!session}
className={`button mt-2 ${
!session && 'from-gray-300 to-gray-500 border-gray-200 text-gray-300 cursor-not-allowed'}`}
>
{!session ? 'Sign in to checkout' : 'Proceed to checkout'}
</button>
</>
)}
</div>
</main>
</div>
)
}
export default checkout
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async(req, res) => {
const { items, email } = req.body;
const transformedItems = item.map((item) => ({
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: item.price * 100,
product_data: {
name: item.title,
description: item.description,
images: [item.image]
},
},
}));
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
shipping_options: [`shr_1M2oWjIlRietTXvq5h1c8DDQ`],
shipping_address_collection: {
allowed_countries: ['USA']
},
items: transformedItems,
mode: 'payment',
success_url: `${process.env.HOST}/success`,
cancel_url: `${process.env.HOST}/checkout`,
metadata: {
email,
images: JSON.stringify(items.map((item) => item.image))
}
});
res.status(200).json({ id: session.id })
}
It looks like your request to Stripe is not adhering to the expected structure, and I suspect looking at the logs in your Stripe dashboard will show a list of failed requests with detailed error messages on why they failed.
items is not a parameter when creating Checkout Sessions, line_items is what you're looking for.
shipping_address_collection.allowed_countries is expecting a two-letter country code, so you want to use US instead of USA.

Svelte with DaisyUI Modal not opening after promise is resolved

I've got a modal which is supposed to open when a link is clicked:
<script>
import AddressForm from "../forms/AddressForm.svelte";
let openModal = false;
let formData = {};
const showModal = async () => {
const id = "bb80b8f9-1de8-431c-9b07-421e462d59e4";
openModal = true;
}
</script>
<div class="flex justify-center">
<a href="#address-modal" on:click={showModal}>
<span class="align-middle edit-color">Edit</span>
</a>
</div>
{#if openModal}
<h1>Test Ttitle</h1>
<div class="modal" id="address-modal">
<div class="modal-box relative w-11/12 max-w-5xl">
<label for="address-modal" class="btn btn-sm btn-circle absolute right-2 top-2">✕</label>
<AddressForm
formData={formData}
isModal={true}
/>
</div>
</div>
{/if}
The code above works fine, when the link is clicked the modal appears. But now I've gotta send some data to the component loaded in the modal, to do so I'm making a call within showModal to a function that returns a promise. After the promise is resolved the modal is not opening:
const showModal = async () => {
// console.log('opening modal')
const id = "bb80b8f9-1de8-431c-9b07-421e462d59e4";
let address = await getAddress(id)
console.log(address)
formData = address;
openModal = true;
}
with the code above the modal does not open. I tried the following as well:
const showModal = async () => {
// console.log('opening modal')
const id = "bb80b8f9-1de8-431c-9b07-421e462d59e4";
let address = await getAddress(id)
.then(address => {
console.log(address)
formData = address;
openModal = true;
});
}
but the result is the same.
Any idea what's going on?

i have an issue with rendering content from graphCMS, the categories in particular

learning how to build a blog with nextjs and graphCMS, been able to get some content using gql queries but for no understandable reason, i can't seem to render the categories.name content onto the site and I am not getting an error. i would like to know what the problem is as I have encountered this prior to this moment with the sanity.io platform for an e-commerce project.
import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import { getCategories } from '../services'
const Categories = () => {
const [categories, setCategories] = useState([]);
useEffect(() => {
getCategories()
.then((newCategories) => setCategories(newCategories))
}, []);
return (
<div className='bg-white shadow-lg rounded-lg p-8 mb-12'>
<h3 className='text-xl mb-8 font-semibold border-b pb-4'>
Categories
</h3>
{categories.map((category) => {
<Link key={category.slug} href={`/category/${category.slug}`}>
<span className='cursor-pointer block pb-3 mb-3'>
{category.name}
</span>
</Link>
})}
</div>
below is the query that I used to set up the process for rendering the content I need to display on the site
export const getCategories = async () => {
const query = gql`
query GetCategories {
categories {
name
slug
}
}
`
const result = await request(graphqlAPI, query);
return result.categories;
}
Assuming you are getting data and the state is correct, you're missing return in your map
{categories.map((category) => {
// notice this return keyword!!
return <Link key={category.slug} href={`/category/${category.slug}`}>
<span className='cursor-pointer block pb-3 mb-3'>
{category.name}
</span>
</Link>
})}
figured it out, had to change {} to () after the .map element and =>

Trying to create a dynamic link with API and React router, console is showing [object%20Object].json 404?

I'm currently working on a site that pulls Reddit data from different subreddits to show recipes, you can toggle between 3 different ones. That part works fine! I'm able to pull the list of posts from each subreddit, but now I'm trying to make it so when you click a button, it routes you to post details where it'll show the post and comments. I have to do another API call to get that information.
Somewhere along the way, it's getting messed up and it's showing "xhr.js:210 GET https://www.reddit.com/r/recipes/comments/[object%20Object].json 404:" It's a dynamic route, so there are two different parameters I'm trying to use. I did try and console log the parameter for ID(the one showing up as [object object] and it shows up fine by itself and is not an object from what I can tell.
Please see some of the code below where I think things could be going wrong. I'm guessing it's the API call because when I console log it, it only shows the subreddit as an arg but not sure..
redditAPI.js:
import axios from 'axios';
export default axios.create({
baseURL:"https://www.reddit.com/r/"
})
store.js:
import {configureStore} from '#reduxjs/toolkit';
import postReducer from './posts/postSlice';
export const store = configureStore({
reducer: {
posts: postReducer
}
});
postSlice.js:
import {createSlice, createAsyncThunk} from '#reduxjs/toolkit';
import redditApi from '../../common/api/redditApi';
import { redditDetails } from '../../common/api/redditApi';
export const fetchAsyncPosts = createAsyncThunk('posts/fetchAsyncPosts', async (subreddit) => {
const response = await redditApi.get(subreddit)
return response.data.data.children;
});
export const fetchAsyncPostsDetail = createAsyncThunk('posts/fetchAsyncPostsDetail', async (sub, postID) => {
const response = await redditApi.get(`${sub}/comments/${postID}.json`)
return response.data.data.children;
});
const initialState = {
posts: [],
selectedSubreddit: 'recipes.json',
selectedPost: []
}
const postSlice = createSlice({
name: "posts",
initialState,
reducers: {
addPosts: (state, { payload }) => {
state.posts = payload;
},
addSelectedPost: (state, {payload}) => {
state.selectedPost = payload;
},
setSelectedSubreddit(state, action) {
state.selectedSubreddit = action.payload;
}
},
extraReducers: {
[fetchAsyncPosts.pending] : () => {
console.log("Pending");
},
[fetchAsyncPosts.fulfilled] : (state, {payload}) => {
console.log("Fulfilled");
return {...state, posts: payload};
},
[fetchAsyncPosts.rejected]: () => {
console.log("Rejected");
},
[fetchAsyncPostsDetail.fulfilled] : (state, {payload}) => {
console.log("Fulfilled");
return {...state, selectedPost: payload};
},
},
});
export const {addPosts, setSelectedSubreddit} = postSlice.actions;
export const selectSelectedSubreddit = (state) => state.selectedSubreddit;
export const getAllPosts = (state) => state.posts.posts;
export const getSelectedPost = (state) => state.posts.selectedPost;
export default postSlice.reducer;
App.js
import "./App.scss";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import PageNotFound from "./components/PageNotFound/PageNotFound";
import Header from "./components/Header/Header";
import Home from "./components/Home/Home";
import PostDetails from "./components/PostDetails/PostDetails";
import Footer from "./components/Footer/Footer";
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div className="App">
<Router>
<Header/>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/:sub/comments/:postID" element={<PostDetails />} />
<Route path="*" element={ <PageNotFound />} />
</Routes>
</Router>
</div>
);
}
export default App;
Home.js:
import React, {useEffect} from 'react'
import { useDispatch, useSelector } from 'react-redux';
import PostListing from '../PostListing/PostListing'
import { fetchAsyncPosts } from '../../features-redux/posts/postSlice';
function Home() {
const dispatch = useDispatch();
const subreddit = useSelector((state) => state.posts.selectedSubreddit);
useEffect(() => {
dispatch(fetchAsyncPosts(subreddit));
}, [dispatch, subreddit]);
return (
<div>
<div className="jumbotron jumbotron-fluid">
<div className="container text-center">
<h1 className="display-4">Welcome to Tasteful Reddit</h1>
<p className="lead">Toggle between subreddits above to view their recipes.</p>
</div>
</div>
<PostListing />
</div>
)
}
export default Home
postListing.js:
import React from 'react'
import { useSelector } from 'react-redux'
import { getAllPosts } from '../../features-redux/posts/postSlice'
import PostCard from '../PostCard/PostCard';
function PostListing() {
const posts = useSelector(getAllPosts);
const rendering = () => posts.map((post, key) => {
return <PostCard key={key} data={post.data} />;
});
console.log(posts);
return (
<div className="post-wrapper">
<div className="post-container">
{rendering()}
</div>
</div>
)
}
export default PostListing
postCard.js:
import React from 'react'
import parse from 'html-react-parser';
import {Link} from 'react-router-dom';
function PostCard(props) {
const {data} = props;
/* Function to change escaped HTML to string */
const htmlDecode = (input) => {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
/* Decode reddit JSON's youtube embed HTML */
const youtubeHtmlString = htmlDecode(data.media_embed.content);
/* This function runs through the reddit data to make sure that there is a
an image for the post. If so, shows image
and if its a reddit hosted video or youtube video it will render the video.
Gallery-style posts & all else shows empty div*/
const mediaRender = () => {
if (data.thumbnail !== 'self' && data.thumbnail !== 'default' && data.is_self !== true && data.is_gallery !== true && data.domain !== 'youtu.be' && data.domain !== 'v.redd.it') {
return <img src = {data.url} alt={data.title} className="card-img-top"/>;
} if ( data.is_video == true) {
return (
<div>
<video controls preload = "none">
<source src={data.media.reddit_video.fallback_url} type="video/mp4"/>
Your browser does not support the video tag.
</video>
</div>
)
} if (data.domain == 'youtu.be') {
return (
<div className="Container">
{parse(youtubeHtmlString)}
</div>
)
} else {
return <div></div>
}
}
/* If only text & no photos, render text info*/
const renderSelf = () => {
if(data.is_self == true) {
return (<p>{data.selftext}</p>)
} else {
return <p></p>
}
}
return (
<div className="card mb-3 mx-auto text-center" style={{width: "70%"}}>
<div className="row g-0">
<div className="col-md-5">
{mediaRender()}
</div>
<div className="col-md-7">
<div className="card-body">
<h5 className="card-title">{parse(data.title)}</h5>
<div className="card-text">{renderSelf()}</div>
<div className="card-text"><small className="text-muted">By {data.author}</small></div>
<Link to={`/${data.subreddit}/comments/${data.id}`}>
<button className="btn btn-primary">Go to post</button>
</Link>
</div>
</div>
</div>
</div>
)
}
export default PostCard
postDetails.js:
import React, { useEffect } from 'react'
import { useParams } from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
import { fetchAsyncPostsDetail, getSelectedPost } from '../../features-redux/posts/postSlice';
function PostDetails() {
let {sub, postID} = useParams();
const dispatch = useDispatch();
const data = useSelector(getSelectedPost);
console.log(postID)
useEffect(() => {
dispatch(fetchAsyncPostsDetail(sub, postID));
console.log(dispatch(fetchAsyncPostsDetail(sub, postID)))
}, [dispatch, postID, sub]);
console.log(data);
return (
<div>
PostDetails
</div>
)
}
export default PostDetails
Any help would be appreciated, because I'm lost!
Thanks!
I figured it out today, for those interested!
I finally got it! I figured I was doing something wrong with react router, and that's why I couldn't get it to work but I didn't want to stop using react router. I tried many different ways to fix it, including putting both arguments in an object, I tried changing it by passing what I needed with a pathname AND a state, but the state didn't work right. think that I was passing the state in an incorrect way somehow. I think I wrote it like state{ permalink: data.permalink} or something. I also tried changing it so it only took one parameter, but for some reason the react router Link only wanted to use the post IDs and would go to my page not found if I tried to use permalink. After researching other ways to pass data using React Router, I landed on using From to grab the data from the previous page the user was on and used useLocation to grab the state.
Here is a snippet of what I changed in Link for in PostCard.js. The data was passed in props from postListing.js, just for reference:
return (
<div className="card mb-3 mx-auto text-center" style={{width: "70%"}}>
<div className="row g-0">
<div className="col-md-5">
{mediaRender()}
</div>
<div className="col-md-7">
<div className="card-body">
<h5 className="card-title">{parse(data.title)}</h5>
<div className="card-text">{renderSelf()}</div>
<div className="card-text"><small className="text-muted">By {data.author}</small></div>
<Link to={`/post/${data.id}`}
state={{ from: data}}>
<button className="btn btn-primary">Go to post</button>
</Link>
</div>
</div>
</div>
</div>
)
}
I also stopped using the postId to try and make the API call, and instead only used it to make the dynamic link to the component. After that, I used From's state to grab the permalink(from previous reddit post data) to make the API call to get the comment information.
Here is a snippet of PostDetails.js where I made the changes:
function PostDetails() {
const location = useLocation();
const {from} = location.state;
const comments = useSelector(getSelectedPost);
const dispatch = useDispatch();
useEffect( () => {
dispatch(getPostComments(from.permalink));
}, [dispatch]);
I also found out I was trying to access the data incorrectly in my API call, as the data was structured differently than I originally thought.
Here is the changed thunk in PostSlice.js:
export const getPostComments = createAsyncThunk('posts/getPostComments', async (permalink) => {
const response = await fetch(`http://www.reddit.com${permalink}.json`);
const json = await response.json();
return json[1].data.children.map((comment) => comment.data)
});
There were multiple things wrong with my react app, but hopefully this helps someone else! :)
The second argument to createAsyncThunk is the payloadCreator.
It's called with two arguments, arg which is a single value, and the thunkAPI object.
// First, create the thunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))
You are passing the thunkAPI argument as the postID value in the GET request.
export const fetchAsyncPostsDetail = createAsyncThunk(
'posts/fetchAsyncPostsDetail',
async (sub, postID) => {
const response = await redditApi.get(`${sub}/comments/${postID}.json`)
return response.data.data.children;
}
);
If you need to pass multiple values to your thunk then pack them into a single object.
export const fetchAsyncPostsDetail = createAsyncThunk(
'posts/fetchAsyncPostsDetail',
async ({ sub, postID }, thunkAPI) => {
const response = await redditApi.get(`${sub}/comments/${postID}.json`)
return response.data.data.children;
}
);
...
useEffect(() => {
dispatch(fetchAsyncPostsDetail({ sub, postID }));
}, [dispatch, postID, sub]);

What do I need to do that appendChild and addEventListener is going to work?

I can see the issue here. Stuff is going to fetch before it's still there in the order of code execution, but I don't know how to fix that at all.
I want to grab some infos from my firebase firestore database and put it in the dom in a way I can show it of nicely.
The other thing is, css file isn't working cause of the same issue. When I setAttribute to it it's already initialized and of course, it wouldn't show up at all (for example: border: 50% to make the pic round).
What do I miss to learn?
import React from "react";
import firebase from "./firebase";
import "./artists-styles.css";
const db = firebase.firestore();
const form = document.querySelector("#add-artist-avatar");
function renderArtists(doc) {
const artistsAvatar = document.querySelector(".content");
let image = document.createElement("img");
image.setAttribute("src", doc.data().avatar);
artistsAvatar.appendChild(image);
}
// getting data
db.collection("artists")
.get()
.then(snapshot => {
console.log(snapshot.docs);
snapshot.docs.forEach(doc => {
console.log(doc.data());
renderArtists(doc);
});
});
// saving data
form.addEventListener("submit", e => {
e.preventDefault();
db.collection("artists").add({
avatar: form.avatar.value,
});
form.name.value = "";
});
const Artists = () => {
return (
<div>
<h1>Cloud Cafe</h1>
<form id="add-artist-avatar">
<input type="text" name="avatar" placeholder="Artists Avatar Link" />
<button>Add Avatar</button>
</form>
<div className="content"></div>
</div>
);
};
export default Artists;
Perhaps you need something like this
import React, { useEffect, useState } from "react";
import firebase from "./firebase";
import "./artists-styles.css";
const db = firebase.firestore();
const Artists = () => {
const [docs, setDocs] = useState([]);
const [inputValue, setInputValue] = useState('');
useEffect(() => {
db.collection("artists")
.get()
.then(snapshot => {
console.log(snapshot.docs);
setDocs(snapshot.docs);
});
}, []);
const handleSubmit = e => {
e.preventDefault();
db.collection("artists").add({
avatar: inputValue
});
};
return (
<div>
<h1>Cloud Cafe</h1>
<form id="add-artist-avatar" onSubmit={(e) => handleSubmit(e)}>
<input
type="text"
name="avatar"
placeholder="Artists Avatar Link"
value={inputValue}
onChange={e => setInputValue(e.target.value)}
/>
<button>Add Avatar</button>
</form>
<div className="content">
{docs.map(doc => (
<img src={doc.data().avatar}/>
))}
</div>
</div>
);
};
export default Artists;

Resources