Why my useState object returns null, although I defined it and set a value to it?

45 views Asked by At

This is the access to my server:

    const {id}=useParams();
    const [card,setCard]=useState({});
    console.log(id);
    // useEffect(()=>{
    //     console.log('Component rendering...');
    //
    // },[id]);
   fetch(`http://localhost:${port}/api/asked/${id}`, {
        method: "GET"
    })
        .then((response) => {
            console.log(response);
            if (response.status === 200) {
                return response.json(); // This returns a Promise
            } else {
                console.log('Request failed with status ' + response.status);
                throw new Error('Request failed with status ' + response.status);

            }
        })
        .then((data) => {
            console.log(data);
            setCard(data); // Call setCards with the data after it has been fully processed
        })
        .catch((error) => {
            console.log(error);
        });

This is the server method:

app.get('/api/asked/:id',(req, res)=>{
    // the key is passed int the request
    const key= req.params.id;
    asked(key).then((result)=>{
        res.send(result);
    });

 }); 

The method is defined like this:

function asked(key){
    return fetch(`https://api.discogs.com/releases/${bigInt(key)}`, {
        method: 'GET',
        headers: {
            'Authorization': authorizationHeader,
        }
    })
        .then((res) => {
            if (!res.ok) {
                throw new Error(`HTTP error! Status: ${res.status}`);
            }
            return res.json();
        })
        .then((data) => MusicAlbum(data))
        .catch((error) => {
            console.error("Error fetching data:", error);
            return {};
        });
} 

The problem is that when I'm trying to read the card variable, I get null, although the response object isn't null. how to fix it?

0

There are 0 answers