i encountered an issue with react app not showing any data in mobile view

45 Views Asked by At

Body.js

import RestaurantCard, { withBestSellerLabel } from "./RestaurantCard";
import { useEffect, useState, useContext } from "react";
import Shimmer from "./Shimmer";
import { Link } from "react-router-dom";
import useOnlineStatus from "../utils/useOnlineStatus";
// import UserContext from "../utils/UserContext";
import Dishes from "./Dishes";
import Footer from "./Footer";


const Body = () => {
    const [listOfRestaurants, setListOfRestaurant] = useState([]);
    const [searchInput, setSearchInput] = useState('');
    const [filteredRestaurant, setFilteredRestaurant] = useState([]);
    const [title, setTitle] = useState('');
    const RestaurantCardBestSeller = withBestSellerLabel(RestaurantCard);
    // const { loggedInUser, setUserName } = useContext(UserContext);

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

    const fetchData = async () => {
        const data = await fetch("https://www.swiggy.com/dapi/restaurants/list/v5?lat=18.9777315&lng=72.8273249&is-seo-homepage-enabled=true&page_type=DESKTOP_WEB_LISTING");
        const json = await data.json();
        console.log(json);
        setTitle(json?.data?.cards[1]?.card?.card?.header?.title);
        setListOfRestaurant(json?.data?.cards[1]?.card?.card?.gridElements?.infoWithStyle?.restaurants)
        setFilteredRestaurant(json?.data?.cards[1]?.card?.card?.gridElements?.infoWithStyle?.restaurants)

    }

    const onlineStatus = useOnlineStatus();
    if (onlineStatus === false) {
        return <h1>Looks like you're offline please check your internet connection</h1>
    }


    return listOfRestaurants?.length === 0 ? (<Shimmer />) : (
        <div className="body">
            <div className="filter flex">
                <div className="searchBar m-4 p-4">
                    <input data-testid="searchInput" type="text" className="border border-solid py-1 pl-1 border-pink-100 rounded-sm" placeholder="Search.." value={searchInput} onChange={(e) => { setSearchInput(e.target.value) }} />
                    <button name="Search" className="px-4 py-1 m-4 bg-pink-100 rounded-lg" onClick={() => {
                        const filteredRestaurant = listOfRestaurants.filter(rest => rest.info.name.toLowerCase().includes(searchInput.toLowerCase()));
                        setFilteredRestaurant(filteredRestaurant)
                    }}>Search</button>
                </div>
                <div className="searchBar p-4 flex items-center">
                    <button className="px-4 py-1 bg-gray-100 rounded-lg" onClick={() => {
                        const filteredList = listOfRestaurants.filter((res) => res.info.avgRating > 4.5);
                        setFilteredRestaurant(filteredList)
                    }}>Top Rated Restaurants</button>
                </div>
            </div>
            <div>
                <Dishes />
            </div>
            <div className="w-full flex justify-between mt-5 font-bold text-2xl">
                <h1 className="ml-11">{title}</h1>
            </div>
            <div className="flex flex-wrap">
                {filteredRestaurant ? (
                    filteredRestaurant.map((restaurant) => (
                        <Link key={restaurant?.info?.id} to={'/restaurants/' + restaurant?.info?.id}>
                            {restaurant.info.avgRating > 4.5 ? (
                                <RestaurantCardBestSeller resData={restaurant} />
                            ) : (
                                <RestaurantCard resData={restaurant} />
                            )}
                        </Link>
                    ))
                ) : null}
            </div>

            <div>
                <Footer />
            </div>
        </div>
    )
}

export default Body;


Dishes.js

import React, { useEffect, useState, useRef } from 'react'
import { GrFormNext, GrFormPrevious } from "react-icons/gr";
import '../../index.css'
import {CDN_URL, DEFAULT_FOOD_IMAGE_URL} from '../utils/constants'


const Dishes = () => {
    const [dish, setDish] = useState([]);
    const [title, setTitle] = useState('');
    const containerRef = useRef(null);
    
    const fetchData = async () => {
        try {
            const data = await fetch("https://www.swiggy.com/dapi/restaurants/list/v5?lat=18.9777315&lng=72.8273249&is-seo-homepage-enabled=true&page_type=DESKTOP_WEB_LISTING");
            const json = await data.json();
            console.log(json);
            setTitle(json?.data?.cards[0]?.card?.card?.header?.title);
            setDish(json?.data?.cards[0]?.card?.card?.imageGridCards?.info || []); // Provide fallback for dish
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

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

    const scrollPrev = () => {
        if (containerRef.current) {
            const containerWidth = containerRef.current.clientWidth;
            const scrollWidth = containerRef.current.scrollWidth;
            const scrollDistance = (scrollWidth - containerWidth) / 4; // Divide by 4 since we want to scroll through 5 images at a time

            containerRef.current.scrollLeft -= scrollDistance;
        }
    };

    const scrollNext = () => {
        if (containerRef.current) {
            const containerWidth = containerRef.current.clientWidth;
            const scrollWidth = containerRef.current.scrollWidth;
            const scrollDistance = (scrollWidth - containerWidth) / 4; // Divide by 4 since we want to scroll through 5 images at a time

            containerRef.current.scrollLeft += scrollDistance;
        }
    };

    return (
        <div>
            <div className='flex justify-between ml-11'>
                <span className='font-bold text-2xl'>{title}</span>
                <div className='mr-[20px] flex text-2xl'>
                    <span onClick={scrollPrev} className='flex items-center justify-center w-8 p-1 h-8 mr-2 cursor-pointer bg-green-300 rounded-full'><GrFormPrevious /></span>
                    <span onClick={scrollNext} className='flex items-center justify-center w-8 p-1 h-8 cursor-pointer bg-green-300 rounded-full'><GrFormNext /></span>
                </div>
            </div>
            {dish.length > 0 && (
                <div className="flex justify-between overflow-x-auto gap-10 ml-32 mr-32 mt-3 hide-scrollbar" ref={containerRef}>
                    {dish.map(({ imageId }) => (
                        <img key={imageId} className="w-[144px] h-[180px] m-auto" src={imageId ? `${CDN_URL}${imageId}` : DEFAULT_FOOD_IMAGE_URL} alt="dish-image" />
                    ))}
                </div>
            )}
        <div>
                    <hr className='w-[85%] mx-auto mt-10' />
        </div>
        </div>
    )
}

export default Dishes

if i open the page in mobile view with help of inspect tool its fetching the data from api but not rendering on page if i open in the browser its working properly if open inspect tool and select mobile view after refreshing its not rendering please give some solution or suggestion if something wrong with styling so mention it (also its not showing on mobile i also open it in mobile but not getting any data on page)

give some hint or solution

normal view

in mobile view

0

There are 0 best solutions below