[SOLVED] getting localStorage data so that I can pass it to apollo query variables but skip query if the variable is empty

Issue

This Content is from Stack Overflow. Question asked by jameshwart lopez

I save product ids in a localstorage to be used in recently viewed component.
My Recently viewed component is below

import { useQuery } from "@apollo/client";
import { getRecentlyViewedProductArr } from "@gb-utils/product/product"
import { RECENTLY_VIEWED } from "@gb-utils/queries/product";
import { useEffect, useState } from "react";


    export default function RecentlyViewed() {
    
        const [recentIds, setRecentIds] = useState([])
    
        const { loading, error, data } = useQuery(RECENTLY_VIEWED, {
            variables: { ids: recentIds }
        })
    
        useEffect(() => {
            setRecentIds(getRecentlyViewedProductArr())
        }, []);
    
        if (loading) {
            return 'Loading';
        }
    
        if (error) {
            return error.message
        }
    
        return (
            <div>{JSON.stringify(data)}</div>
        )
    }

My question is about how I use get the product from wp-graphql using userQuery with the local storage.

Currently I am defining a state to store product ids and on mount of the RecentlyViewed component I update the recentIds by getting the data from localstorage. Is there a better way of doing the code above because I feel like it fetching data from wp without or empty recentIds



Solution

You can use the skip option from the useQuery API: https://www.apollographql.com/docs/react/data/queries/#skip

const [recentIds, setRecentIds] = useState([])
    
const { loading, error, data } = useQuery(RECENTLY_VIEWED, {
  variables: { ids: recentIds },
  skip: recentIds.length === 0
})
    
useEffect(() => {
  setRecentIds(getRecentlyViewedProductArr())
}, []);


This Question was asked in StackOverflow by jameshwart lopez and Answered by vighnesh153 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?