Answer the question
In order to leave comments, you need to log in
How to properly organize useState and useQuery - Apollo/Graphql?
Hello,
I'm trying to organize the filtering of products by a marked category.
The code as a whole works, but not at all as it should.
When you click on the category checkbox, it feels like the page is being updated, the ID is added to the useState[1] array , filtering occurs, but the checkbox itself is not highlighted. When you click on the checkbox of the second category, the same thing happens useState[1, 2] , but when you click again, the checkbox is selected, and the ID is removed from the array useState[1] .
In short, the opposite is true.
Here is the code
const GET_PRODUCTS = gql`
query GetProducts($filterByCategory: [ID]) {
products(filters: {category: {id:{in: $filterByCategory}}}) {
....
}
}
`
const VacanciesPage = () => {
const [selectCategories, setSelectedCategories] = useState([]);
const getSetSelectedCategories = (category) => {
console.log(category);
if(selectCategories.includes(category)){
setSelectedCategories(selectCategories.filter(item => item != category));
return;
}
setSelectedCategories([...selectCategories, category]);
}
useEffect(() => {
console.log(selectCategories);
},[selectCategories]);
const { loading, error, data } = useQuery(GET_PRODUCTS, {
variables: { "filterByCategory": selectCategories},
});
if (loading) return null;
if (error) return `Error! ${error}`;
const { products, categories } = data;
return(
{categories.data.map(category => (
<label key={category.id} className="inline-flex items-center mt-3 mr-3">
<input type="checkbox" className="w-5 h-5" value={category.id} onChange={e => getSetSelectedCategories(+e.target.value)}/><span className="ml-2 text-gray-700">{category.attributes.name}</span>
</label>
))}
);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question