Trying to fetch localized content from Strapi v4 (PostgreSQL) with Apollo GraphQL's useQuery. It works fine when the locale
value is hardcoded, but not when passing it as variable. Docs.
Example #1 (THIS WORKS):
export const GET_CATS = gql`
query GetCategories {
categories( locale: "en") {
data {
id
attributes {
title
}
}
}
}
`;
NOTE: Above works with other locales too, e.g. "de".
Example #2 (NOT WORKING):
export const GET_CATS = gql`
query GetCategories($locale: String) {
categories( locale: $locale ) {
data {
id
attributes {
title
}
}
}
}
export function useCategories() {
const { data, loading, error } = useQuery(GET_CATS, {
variables: { locale: 'en' },
notifyOnNetworkStatusChange: true,
});
return { data, loading, error };
}
`;
Error:
[ApolloError: Response not successful: Received status code 400]
Example #3 (THIS WORKS):
Here I use filters:
, and the variable works:
export const GET_CATS = gql`
query GetCategories($locale: String) {
categories(filters:{ locale: { eq: $locale }}) {
data {
id
attributes {
title
}
}
} } `;
export function useCategories() {
const { data, loading, error } = useQuery(GET_CATS, {
variables: { locale: 'en' },
notifyOnNetworkStatusChange: true,
});
return { data, loading, error }; }
BUT in this case if I use any other variable as locale, e.g. locale: "de"
, than the query returns an empty array. Possibly because not all categories are translated into "de"? But than why does "de" successfully return translated content in Example #1?
Figured it out. Needed to use I18NLocaleCode!
instead of String
as variable type:
query Categories($id: ID, $locale: I18NLocaleCode!) {
...
}