I have a simple search component and handleSearch function:
const { data, loading, error } = useQuery(QUERY_GET_ELEMENTS);
const client = useApolloClient();
<input
onChange={handleSearch}
placeholder="🔎 Search..."
/>
function handleSearch(e) {
const { value } = e.target;
const matchingElements = data.filter(({ name }) =>
name.toLowerCase().includes(value.toLowerCase())
);
client.writeData({
data: {
elements: matchingElements
}
});
}
// rendering the elements looks something like this:
data.elements.map(el => <div>{el.name}</div>
The data comes from a useQuery hook.
The problem is that the search only works in one direction as once the elements are filtered I lose the original list. I need to keep a store of all of the elements that I can filter and render only the filtered ones while persisting the original list.
I'm using apollo for state management and cannot seem to get this working. My first thought was to use client.writeData to duplicate the elements and that would never be modified, however this did not work as expected.
Any help is much appreciated.
You should be able to accomplish this with the useState
hook. This example works for me:
import React, { useState, useEffect } from 'react';
import gql from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks'
const QUERY_GET_ELEMENTS = gql`
{
elements {
id
name
}
}
`;
export default function Test() {
const [isDisplayDataSet, setIsDisplayDataSet] = useState(false);
const [displayData, setDisplayData] = useState([]);
const { data, loading, error } = useQuery(QUERY_GET_ELEMENTS);
useEffect(() => {
if (!loading && !isDisplayDataSet) {
setDisplayData(data.elements);
setIsDisplayDataSet(true);
}
}, [isDisplayDataSet, displayData, data, loading])
function handleSearch(e) {
const { value } = e.target;
const matchingElements = data.elements.filter(({ name }) =>
name.toLowerCase().includes(value.toLowerCase())
);
setDisplayData(matchingElements);
}
if (error) {
console.error(error);
return <h1>There was an error</h1>
}
if (isDisplayDataSet) {
return (
<>
<input
className="form-control mb-3"
onChange={handleSearch}
placeholder="🔎 Search..."
/>
<ul className="list-group">
{displayData.map(el => <li className="list-group-item" key={el.id}>{el.name}</li>)}
</ul>
</>
);
} else {
return '';
}
}
I added some bootstrap classes for styling :)
And here is the quick-and-dirty apollo-server I setup to load some data in:
const { ApolloServer } = require('apollo-server');
const gql = require('graphql-tag');
const fetch = require('node-fetch');
const typeDefs = gql`
type Element {
id: ID!
name: String!
}
type Query {
elements: [Element]!
}
schema {
query: Query
}
`;
const resolvers = {
Query: {
async elements() {
const res = await fetch('https://reqres.in/api/users');
const { data } = await res.json();
const elements = data.map(({ id, first_name, last_name }) => ({ id, name: `${first_name} ${last_name}` }))
console.log('elements', elements);
return elements;
}
}
}
const server = new ApolloServer({
typeDefs,
resolvers
});
server.listen().then(({ url }) => {
console.log('server ready on ' + url);
});