skip to Main Content

I am working on API’s in react native but i have an error ı cannot fix. I am trying to fetch data and convert it to json. That code worked in different project but now not working. Is anybody can fix it?
It’s fetching and working but not show the data that i want. enter image description here

import { useEffect, useState } from "react";

function useFetch (url) {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState (true);
    const [error, setError] = useState();

    const fetchData = async () => {
        try {
            const {response} = await fetch(url);
            const convertedData = await response.json();
            setData(convertedData);
            setLoading(false);
        } catch (error) {
            setError(error.message);
            setLoading(false);
        }
    }

    useEffect(() => {
        fetchData();
    }, [])

    return {data, loading,error};
}


export default useFetch; 

2

Answers


  1. try with axios , npm i axios and read axios docs

    Login or Signup to reply.
  2. fetch returns a Response object which is a Readable Stream. So, we cant directly destructure it. Try this

    const response = await fetch(url);
    const convertedData = await response.json();
    

    or can convert it to a single line as

    const convertedData = await fetch(url).json();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search