I am woking on a Next.js Project and in there I need to read data using an api and for that I have created 1 api route in /pages/api
directory and that Api is using a function from `/store/manipulate.js' and I have imported that particular function in my api Route file but when I request on that api route it is giving me an error.
So, the component below is requesting for data on that api route.
Homepage.jsx
import axios from 'axios'
import { useEffect, useState } from 'react'
import EventList from '../components/events/EventList'
const HomePage = () => {
const [featuredEvents, setFeaturedEvents] = useState([])
useEffect(() => {
(async () => {
const res = await axios.get('/api/getfeaturedevents')
if (res.status(200)) {
console.log(res.data)
setFeaturedEvents(res.data)
return
}
console.log(res.status)
})()
}, [])
return (
<div>
<h1>
The Home Page.
</h1>
<EventList items={featuredEvents} />
</div>
)
}
export default HomePage
Now, the code shown below is the code of api route file
getFeaturedEvents.js
import { fetchFeaturedEvents } from '../../store/manipulate'
const getFeaturedEvents = (req, res) => {
if (req.method === 'GET') {
try {
const data = fetchFeaturedEvents()
res.send(data)
} catch (error) {
console.log(error)
res.status(500).send()
}
}
}
export default getFeaturedEvents
Now, let's take a look at manipulate.js which will just update store.json
present in same folder.
manipulate.js
const path = require('path')
const fs = require('fs')
const readData = () => {
const data = JSON.parse(fs.readFileSync(path.join(__dirname, 'store.json')))
return data
}
export const fetchFeaturedEvents = () => {
let data = readData()
const result = data.filter(event => event.isFeatured)
return result
}
Now, the Error I am getting is...