简体   繁体   中英

API data is not fetched in reactJS

I am creating a simple to-do list application. When I am trying to fetch data from API it shows data in console but when I try to pass data as prop it show TypeError: Cannot read property 'length' of undefined.How can I make sure that my data is fetched?

Here is the code for main component:

import React, { useEffect, useState } from "react";
import { Tasks } from "./Components/Tasks";
import axios from "axios";

export default function Task() {
  const [task, setTask] = useState([]);

  useEffect(() => {
    fetch("/tasks").then(response =>
      response.json().then(data => {
        setTask(data.task);
      })
    );
  }, []);

  return (
    <div>
      <Tasks task={task} />
    </div>
  );
}

Here is the code of component in which data is being as prop:

import React from "react";

export const Tasks = ({ tasks }) => {
  console.log(tasks);
  return <div>{tasks.length}</div>;
};

I noticed this issue. You have got task prop and you're consuming tasks in the component. Is that a typo? If so, replace the following:

<div>
  <Tasks task={task} />
</div>

With:

<div>
  <Tasks tasks={task} />
</div>

If that's not the problem, read about how to handle exceptions.


Please include Exception Handling in your application in the following way to prevent these issues. Also, just curious to know, where are you using axios ?

When you are dealing with asynchronous requests, the data may not always be available. It is always better to replace the following:

<div>
  <Tasks task={task} />
</div>

with something like this (load only when task is not empty or undefined ):

<div>
  {task && <Tasks task={task} />}
</div>

This renders the Tasks component conditionally, only when task is not undefined .

You can also do the same check here:

export const Tasks = ({ tasks }) => {
  console.log(tasks);
  if (!tasks)
    return null;
  return <div>{tasks.length}</div>;
};

Now you have two options to choose from or use both of them. I'll suggest to implement both the logic in both the components.

Another quick tip will be, if you're confused what's happening or where's the mistake, you can do this way:

export const Tasks = ({ tasks }) => {
  console.log(tasks);
  if (!tasks)
    return "tasks prop are null";
  return <div>{tasks.length}</div>;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM