I'm in the process of trying to connect the front end of my MERN application to the back end. The back end works just fine on its own, and I have no problem accessing data by manually executing HTTP requests. Now that I'm trying to connect it to the front end, I seem to be getting stuck everywhere.
My current problem is that when I try to fetch data via HTTP requests, the DOM disappears and displays a blank page.
import React, {useEffect, useState} from "react"
import ItemRequests from "./dataservices/items.js"
function ItemList(props){
[items, setItems] = useState([])
useEffect(() => {
ItemRequests.getAll()
.then(results => {
console.log(results)
setItems(results.data)
})
.catch(e => {
console.log(e)
})
}, [])
return(
<h6>If this prints the issue has been resolved<h6/>
{/*Additional code*/}
)
}
ItemRequests class: contains all the requests specific to the Items collection
import http from "http-config"
class ItemRequests{
getAll(page = 0){
return http.get("?page=" page)
}
}
export default ItemRequests
http-config file
import axios from "axios"
export default axios.create(){
baseURL: "https://localhost:XXXX/route/to/server",
headers: {
"Content-type": "application/json"
}
}
All other routes in the front end are functional. Only this route, which executes HTTP requests is not rendering properly. I'm debugging right now to see if I can gain any further details, but I would appreciate any insight from here.
Edit: According to my browser's console:
Uncaught TypeError: services_items__WEBPACK_IMPORTED_MODULE_1_.default.getAll is not a function
So for some reason JS does not recognize getAll() as a function, even though it is defined.
CodePudding user response:
Your "ItemList" method seems totally broken to me, like you copy/pasted stuff and got it mixed badly.
I didn't try this, but maybe this is the right way:
function ItemList(props) {
[items, setItems] = useState([])
useEffect(() => {
ItemRequests.getAll()
.then(results => {
console.log(results)
setItems(results.data))
}
).catch(e => {
console.log(e)
})
}, [])
}
Maybe you give it a shot?
CodePudding user response:
ItemsRequests
is a class. You cannot invoke a non-static function directly from a class. So, in order for this code to work, you need to do one of two things:
- Instantiate an object of type
ItemsRequest
insideuseEffect()
ItemsRequests request = new ItemsRequests()
request.getAll()
.then(results => {
console.log(results)
setItems(results.data)
})
.catch(e => {
console.log(e)
})
OR 2. Make your getAll()
method in ItemsRequests
a static method
class ItemRequests{
static getAll(page = 0){
return http.get("?page=" page)
}
}
For this program's purposes, it makes more sense to go with the second option.