Home > Blockchain >  ReactJS : import GraphQL queries dynamically based on a State
ReactJS : import GraphQL queries dynamically based on a State

Time:11-16

I query a specific variable called nameTranslated from my schema, It takes the parameter of the locale with is En-CA, Fr-FA etc and gets the desired word in french. And the way I handle this in my frontend reactjs application is like this:

export const App = () => {
const { locale } = useIntl()

const LOAD_TABLE = gql`
query getItems($id: String!) {
  Items(id: $id) {
    id
    notes
    nameTranslate(language:"${l}")
    defaultClass {
      nameTranslate(language:"${l}")
    }
  }
}
`
useEffect(() => {
// a function to fetch LOAD_TABLE 
},[locale])
}

The above code works perfectly fine and whenever I change the locale variable it re fetches the query. But the problem with this is i have many other query I need to work with, my file length becomes too long and hard to manage. At the same time if I pull the file out, I lose the privilage of dynamacally adding a type for nameTranslate.. How can I solve this issue?

CodePudding user response:

You can make it more modular but still dynamic by using custom hooks, for example:

// hooks/useItemsQuery.js
function useItemsQuery(locale) {
  const itemsQuery = useMemo(() => gql`
    query getItems($id: String!) {
      Items(id: $id) {
        id
        notes
        nameTranslate(language:"${locale}")
        defaultClass {
        nameTranslate(language:"${locale}")
        }
      }
    }
  `, [locale])

  return itemsQuery
}

// App.js
export const App = () => {
  const { locale } = useIntl()

  const itemsQuery = useItemsQuery(locale)
  
  useEffect(() => {
    // a function to fetch itemsQuery
  }, [itemsQuery])
}

Or if you need to call outside of React just a normal function will do. I think this won't have a perf impact as es6 tpl literals are cached (the gql`` part) as long as the variables don't change, even inside a function. If that's the case the use of useMemo above is redundant anyway.

function itemsQuery(locale) {
  return gql`
    query getItems($id: String!) {
      Items(id: $id) {
        id
        notes
        nameTranslate(language:"${locale}")
        defaultClass {
        nameTranslate(language:"${locale}")
        }
      }
    }
  `
}
  • Related