NextJS API directory and useState

Viewed 193

I am trying to get

const [data, setData] = React.useState('');
const [pointdata, setPointData] = React.useState('');

in my API directory. however, everytime I try and run the code I get Cannot read properties of null (reading 'useState'

However, the same code there works fine when it is in a /page/myfile.js

How can I put useState and useEffect in an API directory or is their another way to do this?

Why is it an API file because we are posting form data to this.

import React, { useState } from "react";
export default async function gll(req, res) {
  const [data, setData] = React.useState('');
  const [pointdata, setPointData] = React.useState('');
        
}
1 Answers

You cannot use useState and/or useEffect in api directory. Since React is a front-end library you can only use it's hooks in client-side code i.e. /page/[fileName].js. The code that you write inside /api/[fileName].js is back-end code hence you cannot use React.js hooks there

According to official Next.js documentation.

API routes provide a solution to build your API with Next.js.

Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page.

For more info. visit API Routes | Next.js

Related