0

Data is coming but not displaying

enter image description here

[Data is showing in the consel][2]

Following is my useFetch code I just want to display the todo details

import { useEffect, useState } from "react";
const useFetch = url => {
const [data, setData] = useState([]);
useEffect(() => {
    getData();
}, []);
const getData = async () => {
    try {
        const response = await fetch(url)
        const data = await response.json();
        setData(data)
    } catch (error) {
        console.error("Error from Fetch:", error);
    }
  }
  return data;
 }
export default useFetch;
4
  • Can you console.log all the steps. And I would recommend to use react-query fur this exact use case. Check it out. Commented Feb 15, 2021 at 11:37
  • If there is no state updated in your compoennt, then it won't display anything when your fetch is done (If is asynchronous). You might need to add your result in a local state of your component. Commented Feb 15, 2021 at 11:41
  • No since the hook is used, that would trigger a state update. Even async Commented Feb 15, 2021 at 11:42
  • @Domino987 Ok wasn't sure about that, thanks ! Commented Feb 15, 2021 at 11:51

2 Answers 2

1

Since you are returning the todo as an object itself, you cannot extract it but use it as it is:

const todo = useFetch('http://localhost/todos/todosapi/todos/' + id);

Now you can access the properties.

If you want to destructe the return, you have to wrap the response once more:

const getData = async () => {
    try {
        const response = await fetch(url)
        const data = await response.json();
        setData(data)
    } catch (error) {
        console.error("Error from Fetch:", error);
    }
  }
  return {todo: data};
 }

To reduce the amount of calls you have to make and to cache data, check out react-query.

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

Comments

1

At:

const { todo } = useFetch('http://localhost/todos/todosapi/todos/' + id);

You're trying to access property todo of the fetch response.

Based on the JSON response in the inspector network tab, it looks like there's no todo property. That might be why it is undefined.

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.