how do i use the id in mongodb document - react-redux

I am creating an add to cart functionality using redux toolkit. I fetched my data using rtk query and it works fine but my problem is how do I read the mongodb id in my projects. please help.
const initialState = {
cart: []
}
const carttSlice = createSlice({
name: 'cart',
initialState,
reducers: {
addToCart: (state, action)=>{
//check if the item exist in cart
const ItemInCart = state.cart.find((item) => item.id === action.payload.id);
// please note the id cant read
//if item in cart increment the quantity, if not, we push item to cart.
if(ItemInCart){
ItemInCart.quantity++
}else{
//pushing item to cart
state.cart.push({...action.payload, quantity: 1})
}
}
},
I tied not loading the data from nmongodb and it worked

Related

Conditional validation of the input field vue3 vuelidate

I'm building conditional form with vue and stuck on how conditionally validate input field based on the previous users choice. I'll appreciate any help.
in the form I have dropdown menu with payment choices (terminal, payconiq, cash etc).
Second input field is the link user need to add. If user choose terminal, he should add to link input an IP Address. If not - url address.
I receive a paymentId from options with #click, send it to the store and get it from the store with computed property.
The problem is that my vuelidate does not read the condition
const typefromStore = computed(() => paymentStore.paymentType) // here I get typeId from store
const validations = {
description: { required },
type: { required },
link: {
required,
type: typefromStore.value === 1? ipAddress : url // always checks for url and give an error if I need to input IP address
},
}
I read documentation, but I didn't find how to check second input field based on the value of the previous. Only cases when previous field is invalid. But data from dropdown list is always valid.
I need to use the value of 'type' somehow to check conditionally value of link.
Found the solution. May be will help someone. Needed to put validation in computed. No store needed
let newMethod = reactive({
instanceId: 1,
description: '',
type: -1,
link: '',
active: true,
})
const rules = computed(() => {
const localRules = {
description: { required },
type: { required },
link: {},
}
if (newMethod.type === 1) {
localRules.link = {
ipAddress,
}
}
else {
localRules.link = {
url,
}
}
return localRules
})
const v$ = useVuelidate(rules, newMethod, { $autoDirty: true })

Apollo read multiple values from cache

I'm looking for a way to read the value from cache for Apollo. On the page of Apollo, it only show the way to retrieve one as follow:
With readQuery
const READ_TODO = gql`
query ReadTodo($id: ID!) {
todo(id: $id) {
id
text
completed
}
}
`;
// Fetch the cached to-do item with ID 5
const { todo } = client.readQuery({
query: READ_TODO,
variables: { // Provide any required variables here. Variables of mismatched types will return `null`.
id: 5,
},
});
or with readFragment
const todo = client.readFragment({
id: 'Todo:5', // The value of the to-do item's cache ID
fragment: gql`
fragment MyTodo on Todo {
id
text
completed
}
`,
});
However, I can't select more than 1 todo at a time in both of them. I will have an array of IDs I'm not sure how many values will be in it. What is an excellent approach to this problem?

Update the cache of Apollo client 3 when polling not working

I am playing with the cache of #apollo/client v3. Here's the codesandbox.
I am adding a user to a cached list of users using client.writeQuery, and the query has a pollInterval to refetch every few seconds.
I am able to add the user to the list, it does refresh the UI, and I can see the pollInterval working in the network tab of Chrome.
THE PROBLEM
I would expect the list of users to return to its initial state when the polling kicks in, and overwrite the user I added manually to the cache, but it does not.
Apollo config
export const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: new HttpLink({
uri: "https://fakeql.com/graphql/218375d695835e0850a14a3c505a6447"
})
});
UserList
export const UserList = () => {
const { optimisticAddUserToCache, data, loading } = useUserList();
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={() => optimisticAddUserToCache()}>Add User to cache</button>
<ol>
{data?.users.map(user => {
return <li key={user.id}>{user.firstname}</li>;
})}
</ol>
</div>
);
}
useUserList
const GET_USER_LIST = gql`
query Users {
users {
id
firstname
}
}
`;
export const useUserList = () => {
const { loading, error, data, refetch } = useQuery(GET_USER_LIST, {
pollInterval: 4000 // It does poll (check chromes's network tab), but it doesn't seem to overwrite the cache
});
const client = useApolloClient();
const optimisticAddUserToCache = () => {
const newUser: any = {
id: `userId-${Math.random()}`,
firstname: "JOHN DOE",
__typename: "User"
};
const currentUserList = client.readQuery({ query: GET_USER_LIST }).users;
// This works, it does add a user, and UI refreshes.
client.writeQuery({
query: GET_USER_LIST,
data: {
users: [newUser, ...currentUserList]
}
});
};
return { optimisticAddUserToCache, loading, error, data, refetch };
};
Working as expected (almost)
Polled response arrives always with the same data ...
... doesn't result in write to cache (no content compared) ...
... no data change in cache ...
... data property (from useQuery) not updated ...
... no data updated, no component rerendering.
For optimistic update working you need a real mutation, real [persisted] change on remote datasource ... propagated to next polled responses.

Apollo GraphQL Remote and Local Queries

I'm working with apollo local state and hoping for help to better understand it and fix my query
Here is what my local apollo state looks like.
cache.writeData({
data: {
cart: {
items: [],
total: 0,
__typename: 'CART_INFORMATION'
},
}
});
Where item is an array of objects. Each object is in the form of
{
productId: string,
quantity: number
}
When my cart page loads, i want to fetch more details about my cart to display on the page. Here is my query.
export const GET_CART_PRODUCTS_DETAILS = gql`
query productDetails($productIds: [ID]!) {
cartProducts(productIds: $productIds) {
id
name
price
imageUrl
company
quantity #client
}
}
`;
My main concern is here quantity #client. Since the cartProducts query receives an array of ids, i'm not sure how its going to get the quantity of each product from my local state.
Any help/explanation about how to better structure this is appreciated. I have read the docs, but this use case wasn't covered so i don't know if its supported.

Gatsby - making a dynamic query to Contentful

I'm working on a simple e-commerce based on Gatsby and Contentful.
One of my pages is CartPage.
So I'm trying to make a query to Contenful to get the necessary info about my products, so I want to pass a list of product ids that are in the user's cart.
Here's my component and query:
export interface CartPageProps {
data: {
products: GQL.ContentfulProductConnection;
};
}
const CartPage = ({ data }: CartPageProps) => {
const mockCart = [1, 2];
console.log(data);
return (
<IndexLayout>
<Page>
//
// Layout goes here
//
</Page>
</IndexLayout>
)
}
export default CartPage;
const pageQuery = graphql`
query ProductsInCart($mockCart: [Int], $lang: String) {
products: allContentfulProduct(filter: { idProduct: { in: [1, 2] }, node_locale: { eq: "en" } }) {
edges {
node {
id
idProduct
price
title
quantity
photo {
resize(height: 200, width: 200) {
src
}
}
slug
}
}
}
}
`;
Now all I get on a console.log(data) is undefined.
If I do the same query but with useStaticQuery with all the data hardcoded - I get the desired data. But useStaticQuery doesn't accept variables.
Am I doing something wrong here? How can I pass variables to the query and put my data to the props?
Gatsby uses GraphQL at build-time and not for live sites. as said here So it's not intended for making GraphQL queries on the go.

Resources