fetch data in next js
- Import the
useState
and useEffect
hooks from the react
package. - Create a function component and define the state variables using the
useState
hook. - Use the
useEffect
hook to fetch data from an API endpoint when the component mounts. - Use the
fetch
function to make a GET request to the API endpoint and handle the response using the then
method. - Parse the JSON response using the
json
method and update the state variable with the fetched data. - Handle any errors using the
catch
method and update the state variable with an error message if the request fails.