Home > Enterprise >  Dynamic data showing undefined
Dynamic data showing undefined

Time:03-30

in my project, I'm trying, when I click a blog in many blogs. then only that blog will open in another route. and I set that route dynamically. and trying to load data using the find method. but that showing undefined. Please help me. below are my all codes.

this is my blogs page

import React, { useEffect, useState } from "react";
import { Card, Col, Row } from "react-bootstrap";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/pagination";
import { Pagination } from "swiper";
import "./Blog.css";
import ScrollToTop from "react-scroll-to-top";
import { HashLoader } from "react-spinners";
import { Link } from "react-router-dom";

const Blogs = () => {


    const [blogs, setBlogs] = useState([])
    
    useEffect(() => {
        fetch('https://enigmatic-crag-58614.herokuapp.com/blogs')
            .then(res => res.json())
        .then(data=>setBlogs(data))
    },[])
    console.log(blogs);
    
    


    return (
        <div className="container my-5">
        <ScrollToTop smooth color="#FE1A00" viewBox="0 0 250 250" />
           

            <h1 className="text-danger">Blogs</h1>

            {blogs.length === 0 && (
                <h1 className="my-5 py-5">
                  <HashLoader color={'#FE1A00'} loading={true} size={150} />
                </h1>
              )}
                <Row xs={1} md={3} className="g-4">
                    {
                        blogs.map(blog => <Col>
                            <Card className="shadow">
                                <Card.Img
                                    variant="top"
                                    src={blog.imageLink}
                                    className="m-3"
                                />
                                <Card.Body>
                                    <h3 className="text-danger">{blog.heading}</h3>
                                    <Card.Text>
                                        {blog.text.slice(0, 200)}...
                                    </Card.Text>
                                </Card.Body>
                                <strong className="mb-3">
                                    <Link to={`/single-blog/${blog._id}`} className="see-more">
                                        See More <i className="fas fa-arrow-circle-right"></i>{" "}
                                    </Link>
                                </strong>
                            </Card>
                        </Col>)
                    }
                    
            </Row>
            
        </div>
    );
};

export default Blogs;

This is my single blog page

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import "./SingleBlog.css";

const SingleBlog = () => {

    const { id } = useParams;

    const [singleData, setSingleData] = useState([])
    
    useEffect(() => {
        fetch('https://enigmatic-crag-58614.herokuapp.com/blogs')
            .then(res => res.json())
        .then(data => setSingleData(data))
    }, [])
    console.log(singleData);

    const matchedData = singleData.find((singleBlogPost) => singleBlogPost?._id == id)

console.log(matchedData);

    return (
        <div className="single-blog container w-75">
            <div className="image-div mb-5 p-0">
                <img
                    src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Walking_tiger_female.jpg/220px-Walking_tiger_female.jpg"
                    alt=""
                />
            </div>
            <div>
                <h1 className="text-danger">Tiger</h1>
                <p className="text-start fs-5 fw-700">
                    The tiger (Panthera tigris) is the largest living cat species and a member of
                    the genus Panthera. It is most recognisable for its dark vertical stripes on
                    orange fur with a white underside. An apex predator, it primarily preys on
                    ungulates such as deer and wild boar. It is territorial and generally a solitary
                    but social predator, requiring large contiguous areas of habitat, which support
                    .
                </p>
            </div>
        </div>
    );
};

export default SingleBlog;

This is my app.js file

import "./App.css";
import Navigation from "./Components/Navigation/Navigation";

import { BrowserRouter, Route, Routes } from "react-router-dom";

import HomePage from "./Components/HomePage/HomePage";
import AcdmClass from "./Components/AcademicClass/AcdmClass";
import ClassSubject from "./Components/ClassSubjects/ClassSubject";
import Lesson from "./Components/Lesson";
import Footer from "./Components/Footer/Footer";
import Contact from "./Components/Contact/Contact";
import Review from "./Components/Review/Review";
import Blogs from "./Components/Blog/Blogs";
import Signin from "./Components/Signin/Signin";
import Profile from "./Components/Profile/Profile";
import Skills from "./Components/Skills/Skills";
import AuthProvider from "./Contexts/AuthProvider";
import PrivateRoute from "./Components/PrivateRoute/PrivateRoute";
import SingleBlog from "./Components/SingleBlog/SingleBlog";

function App() {
    return (
        <div className="App">
            <AuthProvider>
                <BrowserRouter>
                    <Navigation></Navigation>
                    <Routes>
                        <Route path="/" element={<HomePage></HomePage>}></Route>
                        <Route path="home" element={<HomePage></HomePage>}></Route>
                        <Route path="blog" element={<Blogs></Blogs>}></Route>
                        <Route path="contact" element={<Contact></Contact>}></Route>
                        <Route path="skills" element={<Skills />}></Route>
                        <Route path="others" element={<Skills />}></Route>

                        <Route
                            path="/academic-class"
                            element={
                                <PrivateRoute>
                                    <AcdmClass />
                                </PrivateRoute>
                            }
                        />
                        <Route
                            path="/academicclass/:classnumber"
                            element={
                                <PrivateRoute>
                                    <ClassSubject />
                                </PrivateRoute>
                            }
                        />
                        <Route
                            path="/lesson"
                            element={
                                <PrivateRoute>
                                    <Lesson />
                                </PrivateRoute>
                            }
                        />
                        <Route
                            path="/profile"
                            element={
                                <PrivateRoute>
                                    <Profile />
                                </PrivateRoute>
                            }
                        />

                        <Route
                            path="/review"
                            element={
                                <PrivateRoute>
                                    <Review />
                                </PrivateRoute>
                            }
                        />
                        <Route
                            path="/single-blog/:id"
                            element={
                                <PrivateRoute>
                                    <SingleBlog />
                                </PrivateRoute>
                            }
                        />
                        <Route path="/sign-in" element={<Signin />} />
                    </Routes>
                    <Footer></Footer>
                </BrowserRouter>
            </AuthProvider>
        </div>
    );
}

export default App;

But showing this undefined please see this image

CodePudding user response:

Try putting it in a useEffect like so

useEffect(()=>{
if(singleData){
console.log(singleData);

    const matchedData = singleData.find((singleBlogPost) => singleBlogPost?._id == id)

console.log(matchedData);
}
},[singleData,id])

As initially singleData will be undefined and will be set after API call.

CodePudding user response:

In react, The state of the component only get updated at the first time, So you need to tell the react to get the updated state.

In your singleBlog file -

const [singleData, setSingleData] = useState([])
    
    useEffect(() => {
        fetch('https://enigmatic-crag-58614.herokuapp.com/blogs')
            .then(res => res.json())
        .then(data => setSingleData(data))
    }, [])
    console.log(singleData);

    const matchedData = singleData.find((singleBlogPost) => singleBlogPost?._id == id) //This line will never get the data until you ask the react to update the state (means to update the ```singleData``` array.

console.log(matchedData);

So you need to put the same method inside useEffect, and let the useEffect run whenever the state singleData get updated like this ->

useEffect(() => {
        const matchedData = singleData.find((singleBlogPost) => 
        singleBlogPost?._id == id)

       console.log(matchedData);
    }, [singleData, id]) //you need to add here all the dependencies, so that whenever these values will change you need to update your singleBlog page.

HERE IS YOUR FINAL CODE OF SINGLE BLOG PAGE ->

const SingleBlog = () => {

    const { id } = useParams;

    const [singleData, setSingleData] = useState([])
    
    useEffect(() => {
        fetch('https://enigmatic-crag-58614.herokuapp.com/blogs')
            .then(res => res.json())
        .then(data => setSingleData(data))
    }, [])

useEffect(() => {
        const matchedData = singleData.find((singleBlogPost) => 
        singleBlogPost?._id == id)

       console.log(matchedData);
    }, [singleData, id])
 

    return (
        <div className="single-blog container w-75">
            <div className="image-div mb-5 p-0">
                <img
                    src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Walking_tiger_female.jpg/220px-Walking_tiger_female.jpg"
                    alt=""
                />
            </div>
            <div>
                <h1 className="text-danger">Tiger</h1>
                <p className="text-start fs-5 fw-700">
                    The tiger (Panthera tigris) is the largest living cat species and a member of
                    the genus Panthera. It is most recognisable for its dark vertical stripes on
                    orange fur with a white underside. An apex predator, it primarily preys on
                    ungulates such as deer and wild boar. It is territorial and generally a solitary
                    but social predator, requiring large contiguous areas of habitat, which support
                    .
                </p>
            </div>
        </div>
    );
};

export default SingleBlog;
  • Related