最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Deconstructing values nextjs: ReferenceError: Cannot access 'XXX' before initialization - Stack Ove

programmeradmin3浏览0评论

I am using Apollo Client with Nextjs and would like to deconstruct values for easier reading.

I am trying to do this insisde pages/index.js

import { useQuery } from '~/lib/apollo'
return {
    const { data: { allAwards = []} = {} } = useQuery(allAwards) //ReferenceError: Cannot access 'allAwards' before initialization
    .....
}

lib/apollo

export const useQuery = function(query) {
  const { enqueueSnackbar } = useSnackbar()
  const { options = {} } = sortParams([...arguments])
  const { loading, data: queryData, error, refetch } = HookQuery(query, {
    fetchPolicy: 'cache-and-network',
    ...options,
  })
  let transformData = {}
  if (queryData) transformData = new ApolloClass(queryData).start()
  if (error && !options.noError) hookLogger(enqueueSnackbar, error)
  return {
    queryData,
    error,
    loading,
    data: transformData,
    refetch,
  }
}

data

{
  data: {
   allAwards: []
  }
}

I am using Apollo Client with Nextjs and would like to deconstruct values for easier reading.

I am trying to do this insisde pages/index.js

import { useQuery } from '~/lib/apollo'
return {
    const { data: { allAwards = []} = {} } = useQuery(allAwards) //ReferenceError: Cannot access 'allAwards' before initialization
    .....
}

lib/apollo

export const useQuery = function(query) {
  const { enqueueSnackbar } = useSnackbar()
  const { options = {} } = sortParams([...arguments])
  const { loading, data: queryData, error, refetch } = HookQuery(query, {
    fetchPolicy: 'cache-and-network',
    ...options,
  })
  let transformData = {}
  if (queryData) transformData = new ApolloClass(queryData).start()
  if (error && !options.noError) hookLogger(enqueueSnackbar, error)
  return {
    queryData,
    error,
    loading,
    data: transformData,
    refetch,
  }
}

data

{
  data: {
   allAwards: []
  }
}
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Dec 28, 2019 at 22:50 Jamie HutberJamie Hutber 28.1k54 gold badges194 silver badges313 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

You're using destructuring assignment to declare a variable named allAwards from the value returned by the useQuery hook -- and then you try to pass that same variable to the hook. As the error indicates, you can't use a variable before its declared.

const { data: { allAwards = []} = {} } = useQuery(allAwards)
                ^ this                            ^ same as this

There's no reason to use a query result as the first parameter in useQuery in the first place -- this value should always be a DocumentNode object (which is what's returned when you use the gql tagged template). Maybe you have a naming conflict in there somewhere?

发布评论

评论列表(0)

  1. 暂无评论