일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- solidity
- typeScript
- graphQL
- CSS
- JavaScript
- concept
- express.js
- hardhat
- tailwindcss
- 기준
- error
- useState
- Redux
- SSR
- node.js
- bitcoin
- nextJS
- 삶
- Ethereum
- HTML
- CLASS
- API
- evm
- REACT
- Props
- built in object
- middleware
- blockchain
- web
- Interface
- Today
- Total
ReasonJun
Can I use 'useState' in an async function in 'Nextjs'? 본문
The useState hook is designed to be used within a functional component, and it cannot be used inside an asynchronous function.
In Next.js, async operations are typically handled using the useEffect hook or by using server-side rendering (SSR) or static generation (SG) methods. If you need to perform an asynchronous operation and update state based on the result, you can use the useState hook in a functional component and then perform the async operation within a useEffect hook.
Here's an example of how you can achieve this:
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('your-api-endpoint');
const data = await response.json();
setData(data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
return (
<div>
{data ? (
<div>{/* Render your data here */}</div>
) : (
<div>Loading...</div>
)}
</div>
);
};
export default MyComponent;
In this example, the initial state of data is null, and then the useEffect hook is used to fetch the data asynchronously when the component mounts. Once the data is fetched, it updates the state using the setData function, and the component renders the data accordingly.
getting error "TypeError: Cannot read properties of null (reading 'useState')" on useState usage react
So I'm trying to use useState in my nextjs app, but as soon as I add in the line of code to initialize useState it throws a popup error with the error message: TypeError: Cannot read properties of ...
stackoverflow.com