Home > other >  Unable to retrieve individual blog in react using axios
Unable to retrieve individual blog in react using axios

Time:10-25

I have spent a couple of time trying to figure out why I'm not able to obtain individual blog post detail page using axios. The code does not return any data (It is returning undefined) I have the follow code:

/public
/src
    /components
        /blog
            BlogPosts.js
            BlogDetail.js
            ... 
    App.js
       import BlogDetail from './components/blog/BlogDetail';
   
The routing for the DETAIL_POST is:
<Route exact path='/blog/:id' component={BlogDetail} />
DETAIL_POST COMPONENT

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

export default const BlogDetail = (props) => {
    const [blog, setBlog] = useState({});

    useEffect(() => {
        const slug = props.match.params.id;

        const fetchData = async () => {
            try {
                const res = await axios.get(`https://example.com/blog/${slug}`);
                setBlog(res.data);
            }
            catch (err) {

            }
        };

        fetchData();
    }, [props.match.params.id]);

    const createBlog = () => {
        return {__html: blog.body}
    };

    const capitalizeFirstLetter = (word) => {
        if (word)
            return word.charAt(0).toUpperCase()   word.slice(1);
        return '';
    };

    return (
        <div>
            <div dangerouslySetInnerHTML={createBlog()} />
        </div>
    );
};

BlogPost COMPONENT

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

    useEffect(() => {
        const fetchBlogs = async () => {
            try {
                const res = await axios.get(`${process.env.REACT_APP_API_URL}/blog/post`);
                setBlogs(res.data);
            }
            catch (err) {

            }
        }

        fetchBlogs();
    }, []);
const getBlogs = () => {
        let list = [];
        let result = [];
        
        blogs.map(blogPost => {
            return list.push(
                <div className="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
                    
                        <p className="card-text mb-auto">{blogPost.introduction}</p>
                        <Link to={`/blog/${blogPost.slug}`} className="stretched-link">Read More</Link>
           
                </div>
            );
        });

        for (let i = 0; i < list.length; i  = 2) {
            result.push(
                <div key={i} className='row mb-2'>
                    <div className='col-md-6'>
                        {list[i]}
                    </div>
                    <div className='col-md-6'>
                        {list[i 1] ? list[i 1] : null}
                    </div>
                </div>
            )
        }

        return result;
    };
return (
    <div className="jumbotron p-4 p-md-5 text-white rounded bg-dark">
        {getBlogs()}
    </div>
    );
};

export default Blog;

On checking the browser console I saw this error: Failed to load resource: the server responded with a status of 404 (Not Found) but I can't find where the error is because other components are returning data except the particular one. The code returns data for those I practice with but never works in my case but everything seems to be similar to theirs.

CodePudding user response:

Check the network tab to see the type of response which is fetched or if the request is made or not then make necessary changes.

CodePudding user response:

The solution to the question happens to be simple, I couldn't have made such a mistake. In case anybody encounters similar issue and the frontend seems to work fine, here is the approach I took. I checked serializers.py in the backend app and saw that I did not add slug to the field even if I have slug in blog post models.py. Adding slug to fields in `serializers.py1 fixed the issue

  • Related