import { createContext, useEffect, useState } from "react";

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [userDetails, setUserDetails] = useState(null);

useEffect(() => {
    if (!user) {
        fetchUser(); 
    }
}, [user]);

const getDetails = async (data) => {
    try {
        const res = await fetch(`http://localhost:3000/users/${data.user.id}`, {
            method: 'GET',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json'
            },
        });
        if (res.ok) {
            const data = await res.json();
            setUserDetails(data);
        } else {
            console.log(await res.json());
        }
    } catch (err) {
        console.log(err);
    }
};

const fetchUser = async () => {
    try {
        const res = await fetch('http://localhost:3000/profile', {
            method: 'GET',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        if (res.ok) {
            const data = await res.json();
            setUser(data);
            getDetails(data);

        } else {
            setUser(false);
        }
    } catch (err) {
        console.log(err);
    } finally {
        setLoading(false);
    }
}

return (
    <AuthContext.Provider value={{ user, setUser, loading, setLoading, userDetails }}>
        {children}
    </AuthContext.Provider>
)

}

import { useContext, useEffect, useState } from "react"; import { AuthContext } from "../components/AuthContext"; import { useNavigate } from "react-router-dom"; import Posts from "../components/Posts"; import Aside from "../components/Aside";

const Dashboard = () => { const navigate = useNavigate(); const { user, loading, userDetails } = useContext(AuthContext);

useEffect(() => {
    // Only run when loading is complete and we know whether the user is logged in
    if (!loading) {
        if (!user) {
            navigate('/login');  // Redirect to login if no user is found
        }
    }
    if (loading) {
        navigate('/dashboard');
    }
}, [userDetails, loading , user, navigate]);

if (loading) {
    return <h2>Loading...</h2>;  // Show loading indicator while fetching user data
}

return (
    <section>
        {user && userDetails ? (
            <div className="dashboard-con">
                <Aside />
                <div>

                </div>
                <h1>Hello {userDetails.firstName}</h1>
                <Posts />
            </div>
        ) : null}
    </section>
);

};

export default Dashboard;

import { useContext, useEffect, useRef, useState } from 'react'; import { Editor } from '@tinymce/tinymce-react'; import { AuthContext } from './AuthContext'; import { useNavigate } from 'react-router-dom';

const CreateBlog = () => {

const navigate = useNavigate();
const { user } = useContext(AuthContext);

const [blogData, setBlogData] = useState({
    title: '',
    content: '',
});

const handleChange = (e) => {
    const { name, value } = e.target;
    setBlogData({
        ...blogData,
        [name]: value,
    })
}

const handleEditorChange = (content, editor) => {
    setBlogData(p_state => ({
        ...p_state,
        content: content
    }))
}

const [isEditorReady, setEditorReady] = useState(false);
const [loading, setLoading] = useState(true);
const [isBlogCreated, setBlogCreated] = useState(false);

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
        const res = await fetch(`http://localhost:3000/posts/${user.user.id}/create`, {
            method: 'POST',
            credentials: 'include',
            body: JSON.stringify(blogData),
            headers: {
                'Content-Type': 'application/json',
            }
        })
        if (res.ok) {
            const data = await res.json();
            console.log(data);
            setBlogCreated(true);
        } else {
            setBlogCreated(false);
        }
    } catch (err) {
        console.log(err);
    }
}

function handleEditorLoading() {
    setEditorReady(true);
    setLoading(false);
}


useEffect(() => {
    if (!loading) {
        if (!user) {
            navigate('/login');
            return;
        }
    }
    if (isBlogCreated) {
        navigate('/myblogs');
    }
}, [user, loading, isBlogCreated])

const TINY_API = import.meta.env.VITE_TINYMCE_API_KEY
return (
    <>
    {user ? 
        <div className='blog-editor-container'>
            <form className='blog-form' onSubmit={handleSubmit}> 
                {!isEditorReady ? 
                    <h2>Loading editor...</h2>
                :
                <div className='blog-title'>
                    <label htmlFor="title">Title for the blog</label>
                    <input type="text" name='title' id='title' value={blogData.title} onChange={handleChange} />
                </div>
                }
                <Editor 

                    apiKey={TINY_API}
                    value={blogData.content}
                    init={{
                        height: 500,
                        menubar: false,
                        plugins: [
                            'advlist', 'autolink', 'lists', 'link',
                            'charmap', 'preview', 'anchor', 'searchreplace',
                            'visualblocks', 'code', 'fullscreen', 
                            'insertdatetime', 'media', 'table', 'code',
                            'help', 'wordcount',
                        ],
                        toolbar: 'undo redo | blocks | ' + 
                        'bold italic forecolor | alignleft aligncenter ' +
                        'alignright alignjustify | bullist numlist outdent indent | ' +
                        'removeformat | help',
                        content_style: 'body { fontfamily: sans-serif; font-size: 14px }'
                    }}
                    onInit={handleEditorLoading}
                    onEditorChange={handleEditorChange}

                    />
                <button type='submit' className='submit-btn'>Publish blog</button>
            </form>
        </div>
        : null}

    </>
)

}

export default CreateBlog;

import { useContext, useEffect, useState } from "react"; import { AuthContext } from "../components/AuthContext"; import { useNavigate } from "react-router-dom";

const MyBlogs = () => { const { user, loading } = useContext(AuthContext); const [allBlogs, setAllBlogs] = useState([]); const [error, setError] = useState(false); const navigate = useNavigate();

useEffect(() => {
    if (user) {
        getBlogs();
    }
}, [user]);
useEffect(() => {
    if (!loading) {
        if (!user) {
            navigate('/login')
        }
    }
}, [])

const getBlogs = async () => {
    try {
        const res = await fetch(`http://localhost:3000/posts/${user.user.id}`, {
            method: 'GET',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        if (res.ok) {
            const data = await res.json();
            setError(false);
            console.log(data);
            setAllBlogs(data);
        }
    } catch (err) {
        console.log(err);
        setError(true);
    }
}

if (loading) {
    return <h2>Loading your blogs...</h2>
}

if (error) {
    return <h2 className="error">Error fetching blogs. Try again</h2>
}
return (
    <div className="my-all-blogs">
        <h2>My blogs</h2>
        {allBlogs && allBlogs.length > 0 ? 
            <h2>blogs available</h2> 
            :
            <h2 className="error">No blogs to show <a href="/create">Create new</a></h2>
        }
    </div>

)

}

export default MyBlogs;

the problem is when i login it redirects me to dashboard but there is no content available i have to refresh the page to load content second when i go to myblogs it doesn't display blogs even after refreshing whereas i have blogs in the database and api and endpoints are totally fine