【发布时间】:2020-08-28 04:49:53
【问题描述】:
我正在运行一个抓取脚本(Puppeteer),并希望将每个抓取的行写入数据库。
我目前收到此错误:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
以下是我的代码的相关部分:
import puppeteer from 'puppeteer'
import $ from 'cheerio'
import { useMutation } from '@apollo/react-hooks'
import moment from 'moment'
import gql from 'graphql-tag'
const ADD_RESULT = gql`
mutation CreateOneResult( $site: String!, $status: String!, $link: String!, $name: String, $publication: String, $decision: String, $clause: String, $commentText: String, $decisionText: String, $noDateReceived: Boolean, $dateReceived: DateTime, $noDateConcluded: Boolean, $dateConcluded: DateTime! ) {
createOneResult(data: {
site: $site,
status: $status,
link: $link,
name: $name,
publication: $publication,
decision: $decision,
clause: $clause,
commentText: $commentText,
decisionText: $decisionText,
noDateReceived: $noDateReceived,
dateReceived: $dateReceived,
noDateConcluded: $noDateConcluded,
dateConcluded: $dateConcluded,
}){
id
}
}
`
/**
* Loop results and follow the link, scraping extra info
*/
export async function doExtraScrapeStepsAndAddToDB(results) {
results = await (async () => {
var updatedResults = []
for (let i = 0; i < results.length; i++) {
let result = results[i]
let extraResultInfo = await module.exports.getExtraPageInfoFromLink(result)
if (extraResultInfo) {
let updatedResultInfo = { ...result, ...extraResultInfo }
let added = await addResultToDB(updatedResultInfo)
console.log(`Added result of ID ${added} to the database`)
updatedResults.push(updatedResultInfo)
}
}
return updatedResults
})()
return results
}
/**
* Add result to DB
*/
export async function addResultToDB(result) {
const [CreateOneResult] = useMutation(ADD_RESULT)
return await CreateOneResult({
variables: {
...result,
...(false == result.noDateConcluded && {
dateReceived: moment(result.dateConcluded, 'DD/MM/YYYY').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
}),
...(false == result.noDateReceived && {
dateReceived: moment(result.dateReceived, 'DD/MM/YYYY').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
}),
}
})
}
-
doExtraScrapeStepsAndAddToDB被调用 - 它通过
getExtraPageInfoFromLink获取每个结果的更多信息(来自另一个 URL) - 最后通过
addResultToDB将完成的结果写入DB
我计划在前端使用 GraphQL (Apollo),所以我想我可以在这个抓取脚本中通过在后端使用 GraphQL 突变写入数据库来练习。
除了useMutation 函数只能在函数组件中使用(?)之外,我不太了解错误的性质。如果是这样的话,这里有什么替代方案?
我正在使用:
- GraphQL
- 连结
- 棱镜
- 阿波罗
提前致谢!
【问题讨论】:
标签: node.js reactjs next.js react-apollo prisma-graphql