1

I'm trying to expose the data from a React.js hook as a REST endpoint using Next.js.

I can easily create a REST endpoint using Next.js using the following code at pages/api/index.tsx

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ hello: 'World' });
}

However, when I attempted to return the data from a React.js hook (fetching the data from an external API), I received an error that I can't access React.js hooks outside an React function or custom hook.

Is there any work-around for this? Or should I do something different with the hook in order to be able to retrieve the data in this file?

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const snxjs = useContext(SNXJSContext);
    
  const {
    SNXPrice,
    SNXTotalSupply,
    SNXPercentLocked,
    issuanceRatio,
    activeCRatio,
    totalIssuedSynths,
    
    SNXPriceQuery,
    SNXTotalSupplyQuery,
    issuanceRatioQuery,
    totalIssuedSynthsQuery,
    SNXHoldersQuery,
  } = useSNXInfo(snxjs);

  res.status(200).json({ SNXPrice: SNXPrice });
}

1 Answer 1

3

What you are trying to do seems conceptually incorrect.

What you are trying to do is to use a hook inside a function handler. Your React hook is meant be used inside a React component. While custom hooks are just functions at the end of the day, if you have used React's built-in hooks like useEffect etc inside SNXInfo, it's not going to work outside non-React components.

The other conceptually incorrect thing is you are trying to somehow make some data from the frontend available through an API by directly accessing your frontend's React constructs. But your API and frontend are actually decoupled in Next.js

More details are needed on why you want to do this. But you should consider using a database. You can make a REST endpoint that will update this database. You can call this endpoint from your React component to update it with needed value using a POST request. You can expose this data residing in your database through another endpoint that can take a GET request.

Sign up to request clarification or add additional context in comments.

1 Comment

Within the project I'm working on, data is immediately loaded into a React hook. Being unexperienced with React, I thought it might have been possible to extract the data from the hook and use it in other parts of the application. However, I'll have to write some middleware logic between the data queries and the React hooks that are being created. Thank you for your reponse!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.