Z
Z
zerabora2021-11-25 14:59:26
JavaScript
zerabora, 2021-11-25 14:59:26

Why is there no data fetched (React)?

Help me figure it out, it seems like I'm doing everything as it is written in the off-documentation example, but I get an error: Cannot read properties of null (reading 'map'). You need to make a request to the server, get the data and display it in the DOM.

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [data, setData] = useState(null);

  useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/todos/1')
          .then(res => res.json())
          .then(
            (data) => {
              setIsLoaded(true);
              setData(data);
            },
            (error) => {
              setIsLoaded(true);
              setError(error)
            }
          )
  },[]);

 if(error){
    return <div>Data loading error: {error.message}</div>
  } else if(!isLoaded){
    return <div>Loading...</div>
  } else{
    return (
        <div className="dashboard">
            {data.map(item => (
                <h1>{item.title}</h1>
            ))}
        </div>
    );
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-11-25
@zerabora

The question is meaningless, the data is there.

fetch('https://jsonplaceholder.typicode.com/todos/1')

By specifying id, you get one object. Object, not array. Remove 1.
const [data, setData] = useState(null);

{data.map(item => (

Does a nullmethod exist map? - google it, figure it out. Well, replace nullwith [].

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question