Reputation: 367
Trying to pass my state of sortNew below to the variables in the Apollo query but getting the following 400 ERROR:
Error: Network error: Response not successful: Received status code 400
Update: Here is the error details:
[GraphQL error]: Message: Variable "$orderBy" of type "String!" used in position expecting type "ItemOrderByInput"., Location: [object Object],[object Object], Path: undefined
This is the current code I'm using thats giving me errors.
Trying to get the ALL_ITEMS_QUERY to take the orderBy variable. Am I missing something?
import React, { Component } from "react";
import { Query } from "react-apollo";
import gql from "graphql-tag";
import styled from "styled-components";
import Item from "./Item";
import Pagination from "./Pagination";
import { perPage } from "../config";
import Sort from "./Sort";
const ALL_ITEMS_QUERY = gql`
query ALL_ITEMS_QUERY($skip: Int = 0, $first: Int = ${perPage}, $orderBy: String!) {
items(first: $first, skip: $skip, orderBy: $orderBy) {
id
title
price
description
image
largeImage
}
}
`;
const Center = styled.div`
text-align: center;
`;
const ItemsList = styled.div`
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 60px;
max-width: ${props => props.theme.maxWidth};
margin: 0 auto;
padding-bottom: 80px;
`;
class Items extends Component {
state = {
sortNew: "createdAt_ASC"
};
render() {
return (
<Center>
<Pagination page={this.props.page} />
<Sort />
<Query
query={ALL_ITEMS_QUERY}
variables={{
orderBy: this.state.sortNew,
skip: this.props.page * perPage - perPage
}}
>
{({ data, error, loading }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ItemsList>
{data.items.map(item => (
<Item item={item} key={item.id} />
))}
</ItemsList>
);
}}
</Query>
<Pagination page={this.props.page} />
</Center>
);
}
}
export default Items;
Upvotes: 0
Views: 1227
Reputation: 36
ALL_ITEMS_QUERY expects orderBy to be an enum like so orderBy: createdAt_ASC
but you're passing in a string orderBy: String!
. To solve this problem, pass in the enum name to ALL_ITEMS_QUERY
, that way, your orderBy can be changed dynamically.
An example will look like this
const ALL_ITEMS_QUERY = gql`
query ALL_ITEMS_QUERY($skip: Int = 0, $first: Int = ${perPage}, $orderBy: NameOfItemsEnum) {
items(first: $first, skip: $skip, orderBy: $orderBy) {
id
title
price
description
image
largeImage
}
}
`;
where NameOfItemsEnum
is the name given to the enum type on the Backend
Upvotes: 1