Search products with graphql and show results with React

OmDev
New Member
3 0 1

Hello,

I want to give the app user the option to search in his products.

I want to fetch the products when the user is typing.

It's working buy only if I'm adding the search term manually

Have a look on my code here:

function ProductsPage() {
    // useEffect
    const PRODUCTS_QUERY = gql`{
      products(first: 20, query: "test") {
        edges {
          node {
            id
            title
              images(first:1) {
                pageInfo {
                      hasNextPage
                  hasPreviousPage
                }
                edges {
                  cursor
                  node {
                    originalSrc
                    id
                  }
                }
              }  
          }
        }
      }
    }`;
    const {loading, error, data} = useQuery(PRODUCTS_QUERY);
    // search field vars
    const [searchValue, setSearchValue] = useState('');
    const handleSearchChange = useCallback((newValue) => {
      setSearchValue(newValue);
      console.log(newValue);
    }, []);

    // set search field
    const searchField = (
      <TextField 
      label="Search for product"
      value={searchValue}
      onChange={handleSearchChange}
      />
    );

    if (loading) return (
        <Loading/>
    );

    if (error) return (
        <Banner status="critical">
            There was an issue loading products.
        </Banner>
    );

    return <ProductsList data={data} searchField={searchField}/>
}

export default ProductsPage;

 

I want that when people typing in searchField component it will make a new request and search for more results.

Replies 0 (0)