Home > Net >  React: can't access property "slug", _ref is undefined
React: can't access property "slug", _ref is undefined

Time:07-24

This code should effect in the display of the blog content according to the slug. After modification and execution of the code the error "Unhandled Rejection (TypeError): can't access property "slug", _ref is undefined" has occurred. Can you help?

The code for BlogDetail.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
    
function BlogDetail() {
    // blogs is the data, setBlogs is a function that sets the value of blogs
    const [blogs, setBlogs] = useState([]);
    
    useEffect(() => {

      const fetchBlogs = async({slug}) => { 
        try {
          const res = await axios.get(`http://localhost:8000/api/blog/${slug}`);
          setBlogs(res.data);
        } catch (err) {}
     };
  
      fetchBlogs();
    }, []);

    const createBlog = () => {
        return {__html: blogs.content}
    };
  
    return (
      <div className="container-m-3">
        {blogs.map((BlogPost, slug) => (
          <article key={slug}>
            <Link to={`/blog/${BlogPost.slug}`} className="stretched-link">{BlogPost.title}</Link>
            <h1 className="display-2">{BlogPost.title}</h1>
            <h2 className="text-muted mt-3">Category: {capitalizeFirstLetter(BlogPost.category)}</h2>
            <h4>{BlogPost.month} {BlogPost.day}</h4>
            <p>Written by {BlogPost.author}</p>
            <div className='mt-5 mb-5' dangerouslySetInnerHTML={createBlog()} />
            <hr />
            <p className="lead mb-5">
              <Link to="http://localhost:8000/api/blog/" className="font-weight-bold">
                Front Page
              </Link>
            </p>
          </article>
        ))}
      </div>
    );
  }
  
  const capitalizeFirstLetter = (word) => {
    if (word) return word.charAt(0).toUpperCase()   word.slice(1);
    return "";
  };
  
  export default BlogDetail;

The code for App.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Layout from './hocs/Layout';
import Home from './components/Home';
import Blog from './components/Blog';
import BlogDetail from './components/BlogDetail';
import Category from './components/Category';

const App = () => (
    <Router>
        <Layout>
            <Routes>
                <Route path='/' element={<Home/>} />
                <Route path='/blog' element={<Blog/>} />
                <Route path='/blog/:id' element={<BlogDetail/>} />
                <Route path='/category/:id' element={<Category/>} />
            </Routes>
        </Layout>
    </Router>
);

export default App;

And the code for .env

REACT_APP_API_URL = 'http=//localhost:8000'
REACT_EDITOR=fathom 

CodePudding user response:

When calling the fetchBlog function in the useEffect, you didn't pass in the slug parameter

CodePudding user response:

You need to put your arguments value in below method inside your useEffect method.

      fetchBlogs(); // here pass your slug value 

Error is mentioned that slug is undefined.

Use this method and it will solve your problem. Just pass your slug value.

const [blogs, setBlogs] = useState([]);
    
    useEffect(() => {

      const fetchBlogs = async(slug) => { 
        try {
          const res = await axios.get(`http://localhost:8000/api/blog/${slug}`);
          setBlogs(res.data);
        } catch (err) {}
     };
     const slugData = window.location.href.split("/");
  
      fetchBlogs(slugData[slugData.length-1]);// add your slug value in this method as an argument
    }, []);

Another problem in this method :-

const createBlog = () => {
        return {__html: blogs.content} //__html is also undefined. use like this "__html" instead of __html
    };

replace this line

{blogs.map((BlogPost, slug) => (

with this

 {(blogs || []).map((BlogPost, slug) => (
  • Related