Altair312
Altair312

Reputation: 348

Cannot fetch properly data from API

I am currently trying out React for a future project and trying to get myself up to speed on it.

Bear with me, due to some circumstances I didn't code for 2 years so I am extremely rusty.

Anyway, I need to get React to properly fetch some data about tasks written up, but no matter what I try it just doesn't work. I have a function written as

  getDataFromDb = () => {
fetch("http://127.0.0.1:8080/api/getTask")
  .then(response => response.json())
  .then(data => this.setState({ tasks: data.tasks, isLoading: false }))
  .catch(error => this.setState({error, isLoading: false}));
};

Now my output inside the JSX file

<React.Fragment>
  <h1>Random User</h1>
  {error ? <p>{error.message}</p> : null}
  {!isLoading ? (
    tasks.map(task => {
      const { title, description } = task;
      return (
        <div key={title}>
          <p>Title: {title}</p>
          <p>Desc: {description}</p>
          <hr />
        </div>
      );
    })

  ) : (
    <h3>Loading...</h3>
  )}
</React.Fragment>

No matter what I try with my own database, it just doesn't want to work with React. I try API calls through Postman and everything gets sent and received without any problems, but React sends out an error "Failed to fetch".

In my server.js I have the following api call written

router.get("/getTask", (req, res) => {
Task.find((err, task) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, task: task });
  });
});

I have scoured Internet and Stack for some answers and examples, and, the dumbest thing is, if I use an external API (such as "https://hn.algolia.com/api/v1/search?query=redux"), or any other, honestly, then it works fine. If it makes any difference, I use mLabs sandbox for MongoDB.

Any suggestions? Been stuck on this for the last 5 hours or so.

Upvotes: 0

Views: 1397

Answers (2)

aromanarguello
aromanarguello

Reputation: 766

You need to call getDataFromDb() inside your component at any point during the lifecycle or if it's tied to an event, such as onClick on a button etc.

If you need it to load initially and your component is a function you can do the following

import React, {useState} from 'react;

function Component() {
 useState(() => {
   getDataFromDb,[])
return (
 <React.Fragment>
  <h1>Random User</h1>
  {error ? <p>{error.message}</p> : null}
  {!isLoading ? (
    tasks.map(task => {
      const { title, description } = task;
        <div key={title}>
          <p>Title: {title}</p>
          <p>Desc: {description}</p>
          <hr />
        </div>
     })

   ) : (
    <h3>Loading...</h3>
   )}
  </React.Fragment>
 )
}

or inside componentDidMount() if you are using a class component

The axios library is really good wrapper for fetching data :)

Upvotes: 0

Nerdragen
Nerdragen

Reputation: 3174

Your fetch request seems to be going to a localhost address and port. Make sure CORS is is set up correctly on your server to allow for incoming connections from the same address with a different port. Postman usually works for any server set up correctly regardless of CORS settings. I'm not sure about fetch, but with axios, if you print the error object, it should give you a lot more information to work with.

In addition, stever's comment is also correct in that tasks is not defined since you're not using this state task.

Upvotes: 1

Related Questions