Home  >  Q&A  >  body text

Passing data using React

In the code below "CameraPage.tsx", a logic is made. Its function is to search for camera images. It is very simple. It just sends a GET request to search for images registered in the backend. The front-end display and operation will be introduced later. correct.

When the user clicks on the "InfoOutlineIcon", another page should load, showing the image, but when clicking on it, another page opens, but does not show the image. The problem that arises is that when you click, the console.log shows that the image is loaded, but when a new page is opened, it seems like everything starts from scratch and no requests are made, so no image is loaded/displayed on the frontend.

// CameraPage.tsx FILE CODE
function CameraPage() {
  const fetchCameraImage = async (cameraId: number, currentPageImages: number): Promise<boolean> => {
    if (!accessToken) {
      console.log("Access token not found");
      return false;
    }

    try {
      console.log("Calling responseFetchCameraImage");
      let responseFetchCameraImage;
      const page = currentPageImages > 0 ? currentPageImages : 1;
      const size = 20;

      responseFetchCameraImage = await axios.get(`${API_URL}/api/v1/imagens/pagination/${cameraId}?page=${page}&size=${size}`, {
        headers: {
          Authorization: `Bearer ${accessToken}`
        },
      });

      console.log(responseFetchCameraImage)
      if (responseFetchCameraImage.status === 200) {
        const images = responseFetchCameraImage.data.items;
        const cameraImages = images.filter((image: any) => image.camera_id === cameraId);
        console.log(cameraImages)

        if (cameraImages && cameraImages.length > 0) {
          const uniqueImagesData: ImageData[] = [];
          cameraImages.forEach((image: any) => {
            const imageData: ImageData = {
              imageURL: `data:image/jpg;base64,${image.image}`,
              data: image.data,
              placa: image.placa,
              score: image.score,
            };
            uniqueImagesData.push(imageData);
          });

          setImageData(uniqueImagesData);

          console.log("Images found");
          return true;
        } else {
          console.error("This camera has no images yet");
          return false;
        }
      } else {
        console.error("Error while trying to fetch camera images");
        return false;
      }
    } catch (error) {
      console.error("Error while trying to fetch camera images");
      errorTimeout = setTimeout(() => {
        setError("");
      }, 3000);
      return false;
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      if (editingCameraId !== null) {
        const success = await fetchCameraImage(editingCameraId, currentPageImages);

        if (success) {
          setCurrentPageImages(1);
          setImageCounter(0);
        }
      }
    };

    fetchData();
  }, [editingCameraId, currentPageImages]);

  return (
    <Layout>
      <Flex justifyContent='center' alignItems='center'>
        <IconButton
          aria-label="View images"
          size="sm">
            <InfoOutlineIcon
              onClick={async () => {
              const hasImage = await fetchCameraImage(camera.id, currentPageImages);
              if (hasImage) {
              routerAfterClickInfoCamera.push('CameraImages')
              }
            }}
          />
        </IconButton>
      {camera.name}
    </Flex>
</Layout>
  );
}

export default CameraPage;

The code below "CameraForm.tsx" is where the image should be displayed, using routerAfterClickInfoCamera.push('CameraForm') you will be taken to the page, however, nothing is displayed as shown below Said before. But I don't understand how to do it, I've been researching but I don't understand it, if anyone can help me I'd be grateful.

// CameraForm.tsx FILE CODE
export interface ImageData {
  imageURL: string;
  data: string;
  placa: string;
  score: number;
}

interface CameraModalProps {
  imageData?: ImageData[];
  currentPageImages: number;
  imagesPerPage: number;
}

const CameraImages: React.FC<CameraModalProps> = ({
  imageData = [],
  currentPageImages,
  imagesPerPage,
}) => {

  const [searchPlaca, setSearchPlaca] = useState("");

  const startIndex = (currentPageImages - 1) * imagesPerPage;

  const endIndex = startIndex + imagesPerPage;

  // Filter images by placa
  const filterImagesByPlaca = () => {
    if (searchPlaca === "") {
      return imageData;
    }

    return imageData.filter((image) =>
      image.placa.toLowerCase().includes(searchPlaca.toLowerCase())
    );
  };

  // Get images filtered by placa
  const filteredImages = filterImagesByPlaca();

  const visibleImages = filteredImages.slice(startIndex, endIndex) ?? [];

  return (
    <Layout>
      <Head title={"Câmeras"} />
      <Flex justifyContent="space-between">
        <Title title="IMAGEM" />
      </Flex>

      <Box>
        <Input
          type="text"
          border="none"
          style={{
            marginLeft: "1rem",
            outline: "none",
            backgroundColor: "transparent",
            borderBottom: "1px solid #ccc",
          }}
          width="auto"
          placeholder="Buscar placa"
          value={searchPlaca}
          onChange={(e) => setSearchPlaca(e.target.value)}
        />
      </Box>
      <Box>
        {visibleImages.map((imageData, index) => {
          const { imageURL, data, placa, score } = imageData;
          const imageNumber = startIndex + index + 1;
          return (
            <Box key={index} borderBottom="1px solid #ccc" py={2}>
              <Text fontSize={["sm", "md"]} fontWeight="normal">
                Imagem {imageNumber}
              </Text>
              <Text fontSize={["sm", "md"]} fontWeight="normal">
                Data: {data}
              </Text>
              <Text fontSize={["sm", "md"]} fontWeight="normal">
                Placa: {placa}
              </Text>
              <Text fontSize={["sm", "md"]} fontWeight="normal">
                Score: {score}
              </Text>
              <ChakraImage src={imageURL} alt={`Image ${index}`} />
            </Box>
          );
        })}
      </Box>
    </Layout>
  )
}

export default CameraImages;

P粉696891871P粉696891871373 days ago463

reply all(1)I'll reply

  • P粉464113078

    P粉4641130782023-09-15 16:45:39

    I think the problem is that you are calling the "CameraImages" component, but you are not sending the props. That's why the image doesn't show up.

    You should do something like this.

    <CameraImages imageData={imageData} currentPageImages={currentPageImages} imagesPerPage={imagesPerPage} />

    reply
    0
  • Cancelreply