GraphQL filter query in react app with https://countries.trevorblades.com/ api

31 Views Asked by At

I'm using https://countries.trevorblades.com/ api.

Using React to do query

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>
  );
}

Is there any better apporche then just add if statement to choose querty in

  const { data } = useQuery(COUNTRIES);

Like

if some value == true ? COUNTRIES : COUNTRIES_FILTER

I'm new to graphQL, current api do not show any results if passed variable is null.

Please advise.

1

There are 1 best solutions below

2
Nazrul Chowdhury On BEST ANSWER

Instead of using an if statement to conditionally choose which query to use based on a value, you can dynamically define the query based on whether the filter variable is provided or not. You can do this by utilizing GraphQL variables directly within the query itself. Something like this,

// 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

You can also consider the option to pass some default value for the filter when it's null

filter: filter ?? 'someDefaultValue' // provide a default value if filter is null