Reputation: 67
I'm trying to send data from a JSON file available on the server side, to the front end. The data is available on the back end when called on Postman, however when I call listPhones() on the front, it's returning as undefined. I hope this is clear enough:
Back end route:
const express = require('express');
const router = express.Router();
const data = require('./../data/phones.json');
router.get('/', (req, res, next) => {
res.json({ data });
});
---------------------------------------------------------
Front end proxy (the base URL is mounted on "api"):
import api from './api';
export const listPhones = () => {
api.get('/phones').then(response => response.data);
};
--------------------------------------------------------
Page to be rendered using listPhones a service:
const [phones, setPhones] = useState([]);
useEffect(() => {
listPhones().then(data => {
setPhones(data.phones);
});
}, []);
Upvotes: 0
Views: 154
Reputation: 13289
Your listPhones
function should return the Promise
if you want to handle the response in the useEffect
:
export const listPhones = () => {
return api.get('/phones');
};
You should then be able to access the data with:
useEffect(() => {
listPhones().then(response => {
setPhones(response.data);
}).catch(err => console.log(err));
}, []);
Upvotes: 1