使用 https://countries.trevorblades.com/ api 在 React 应用程序中进行 GraphQL 过滤器查询

问题描述 投票:0回答:1

我正在使用 https://countries.trevorblades.com/ api。

使用React做查询

export const COUNTRIES = gql`
    query {
        countries {
            code
            name
        }
    }
`;


export const COUNTRIES_FILTER = gql`
    query ListCountries($filter: String) {
        countries(filter: { 
        code: { eq: $filter }
        }) {
        code
        name
        }
    }
`;
import { useQuery } from '@apollo/client';

function App() {

  
  const { data } = useQuery(COUNTRIES);

  return (
    <div className="App">
    </div>
  );
}

有没有更好的apporche然后只需添加if语句来选择查询

  const { data } = useQuery(COUNTRIES);

喜欢

if some value == true ? COUNTRIES : COUNTRIES_FILTER

我是 graphQL 新手,如果传递的变量为 null,当前的 api 不会显示任何结果。

请指教。

reactjs graphql
1个回答
0
投票

您可以根据是否提供过滤变量来动态定义查询,而不是使用 if 语句根据值有条件地选择要使用的查询。您可以通过直接在查询本身中使用 GraphQL 变量来做到这一点。像这样的东西,

// define a single query that accepts a filter variable
export const COUNTRIES_QUERY = gql`
  query ListCountries($filter: String) {
    countries(filter: { 
      code: { eq: $filter }
    }) {
      code
      name
    }
  }
`;

function App() {
  // define your filter variable state, you can set it to null initially
  const [filter, setFilter] = useState(null); 
  
  // dynamically define the query based on whether the filter is provided
  const { data } = useQuery(COUNTRIES_QUERY, {
    variables: {
      filter: filter || null, // pass null if filter is not provided
    },
  });
   return // ...render your component here
© www.soinside.com 2019 - 2024. All rights reserved.