0

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.

3
  • 1
    In tasks.map(), tasks is not defined. Either deconstruct state or use this.state.tasks.map() (assuming your JSX is the same component as the fetch) Commented Mar 31, 2019 at 14:26
  • if postman calls are fine, then probably CORS issue. Try your application on firefox and open the console tab to confirm if it's indeed cors issue. Read how to set up cors here stackoverflow.com/questions/7067966/how-to-allow-cors Commented Mar 31, 2019 at 15:39
  • Fixed this! Thought about the fact, that my authorization snippet works fine, but this doesnt. Turns out, instead of calling http://127.0.0.1:8080/api/getTask, had to call api/getTask instead. Thanks for all the tips! Commented Apr 5, 2019 at 17:28

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 :)

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.