php – How to dynamically get the images from database into react carousel?-ThrowExceptions

Exception or error:

I have an API in PHP for getting the images and want to display it in the react carousel. I don’t know where am I doing wrong but the images won’t display on the carousel. I am trying this thing for the last three days but end up displaying nothing. Can somebody please help me.

import React from "react";
import {Link} from "react-router-dom";
import "./cropSelection.css";
import Carousel, { Dots } from '@brainhubeu/react-carousel';
import '@brainhubeu/react-carousel/lib/style.css';
import 'react-image-picker/dist/index.css'
import axios from 'axios';

class CropSelection extends React.Component {
handleChange = selectedOption => {
  this.setState({ selectedOption });
  console.log(`Option selected:`, selectedOption);
};
constructor(props) {
  super(props)
  this.state = {
    selectedOption: null,
    image: "",
    slides: []
      //(<img src = "https://i.postimg.cc/wjfpKgHg/Apple-1.png" className="fruit-images" alt="Pomegranate fruit" />)
  }
  this.onPick = this.onPick.bind(this);
}
componentDidMount = () => {

  fetch('http://localhost/fruit_api/carousel_api.php')
  .then((response) => response.json())
  .then(data => {
    console.log(data)
    let slides = data.map((pic) => {
      return(
        <div key = {pic.img}>
          <img src = {pic.img} />
        </div>
      )
    })
    this.setState({
      slides: slides
    })
    console.log("state", this.state.slides);
  })
  .then(function(response){
    console.log(response)
  })
  .catch(function(response){
    console.error(response)
  });
}

onPick = (image) => {
  this.setState({image})
}    

render() {
     return (
         <div className="caurosel-div">

         <Carousel
          arrows
          slidesPerScroll={1}
          slidesPerPage={3}
          value={this.state.value}
          slides = {this.state.slides} 
          onChange={this.onchange}
          >
     </Carousel> 
    <Dots value={this.state.value} onChange={this.onchange} number={this.state.slides.length} />
    </div>
   );
  }
}

output

carousel.php

<?php
include_once('database/include.php');
$conn = mysqli_connect("localhost", "root", "", "farmer_portal");

if(!$conn)
    die("Error connecting to DB". mysqli_connect_error());

if($_SERVER['REQUEST_METHOD'] == "GET")
{
    $sel = "SELECT link from images";

    $res = mysqli_query($conn, $sel);

    if(mysqli_num_rows($res) > 0)
    {
        $users = array();
        while($rows = mysqli_fetch_assoc($res))
        {
            $details=array(
                "img" =>  $rows['link']
            );
            array_push($users, $details);
        }
        sendResponse(200,$users,'Images');
    }
    else 
    {
        sendResponse(404,[],'Images not available');
    }
}
?>

developer tool's

developer’s tools image

How to solve:

Figured the problem is in the assignment of the data. The data object consists of the whole response body and because of that the map function could not work. The better way to write this would be

fetch('http://localhost/fruit_api/carousel_api.php')
    .then((response) => response.json())
    .then(data => {
       const { data } = data // getting data attribute out of the response object
       let slides = data.map((pic, k) => {
           return(
              <div key = {k}>
                  <img src = {pic.img} />
              </div>
           )
       })
      this.setState({
         slides //this is interpreted as {slides: slides}
      })

  }).catch(function(response){
       console.error(response)
  });

Leave a Reply

Your email address will not be published. Required fields are marked *