skip to Main Content

im in need of some react help. I currently work as a backend developer but ive recently been trying to get into some front end work. So im just try to build a small project using some NASA Api’s with a Spring boot backend and react frontend. My backend is working find. but being realitivly new to frontend im having some troubles. When i start up my server i get the proper backend response but i get an error from my front end telling me that ‘setApodData’ is not a function and theres just a blank white page. ive added logs to see where it breaks and I can see the data is being logged but not being passed to the setApodData, it seems after the ‘console.log("after await");’ log it stops and throws the setApodData is not a function error ive been searching and using all the AI’s to try to find a soultion and everywhere i look it tells me that my code looks correct. the code i attached below is using react with the materialUI library. I will also attach the console logs and network logs. I have attached code and screenshots below. The backend is being called fine. Im really scratching my head. if you need any additional info let me know. Thanks!

import React,{useEffect,useState} from "react";
import { Card, CardContent,CardMedia, Typography } from "@mui/material";


const ApodCard = () =>{
    const  {apodData, setApodData} = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            try{
                console.log("before response");
                const response = await fetch('http://localhost:8080/get-apod');
                console.log("after response");
                if(!response.ok){
                    throw new Error('HTTP error!, Status: ${response.status}');
                }
                console.log("before await");
                const data = await response.json();
                console.log("Fetched data:", data);
                console.log("after await");
                setApodData(data);
                console.log("after setApodData");
                console.log("Fetched data:", data);
            }catch(error){
                console.error('Error fetching data: ', error);
            }
        };
        fetchData();
    },
   [] );

   return(
    apodData && (
        <Card>
        {apodData.media_type === 'image' ? (
          <CardMedia
            component="img"
            image={apodData.hdurl}
            alt={apodData.title}
          />
        ):(<CardContent></CardContent>)}


        </Card>
    )
   )
};
export default ApodCard;

Console
Network tab

ive added logs to see where it breaks and it seems after the ‘console.log("after await");’ log it stops and throws the setApodData is not a function error ive been searching and using all the AI’s to try to find a soultion and everywhere i look it tells me that my code looks correct.

2

Answers


  1. You should be setting state like this

    const [apodData, setApodData] = useState(null);
    

    The destructed variables should be in an array []

    Login or Signup to reply.
  2. { apodData, setApodData } = useState(null); replace this with

    const [apodData, setApodData] = useState(null);
    

    useState returns an array with two elements: the current state value and a function to update that state. Use array destructuring to assign these values to apodData and setApodData.

    So the corrected version would be,

    import React, { useEffect, useState } from "react";
    import { Card, CardContent, CardMedia, Typography } from "@mui/material";
    
    const ApodCard = () => {
        const [apodData, setApodData] = useState(null);
    
    useEffect(() => {
        const fetchData = async () => {
            try {
                console.log("before response");
                const response = await fetch('http://localhost:8080/get-apod');
                console.log("after response");
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                console.log("before await");
                const data = await response.json();
                console.log("Fetched data:", data);
                console.log("after await");
                setApodData(data);
                console.log("after setApodData");
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        };
        fetchData();
    }, []);
    
    return (
        apodData && (
            <Card>
                {apodData.media_type === 'image' ? (
                    <CardMedia
                        component="img"
                        image={apodData.hdurl}
                        alt={apodData.title}
                    />
                ) : (
                    <CardContent>
                        <Typography variant="body2" color="textSecondary" component="p">
                            {apodData.explanation}
                        </Typography>
                    </CardContent>
                )}
            </Card>
        )
    );
    };
    
        export default ApodCard;
    

    I added Typography component to render text if the media isnt always an image.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search