0

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);
    });
  }, []); 

1 Answer 1

1

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));
  }, []); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.