devs. so I'm pretty new to React and was trying to implement a simple blog app using ReactJS.
I'm having a problem with my useEffect hook.
import { useContext, useEffect } from "react";
import BlogContext from "../../store/blogs-context";
const BlogList = () => {
const blogCtx = useContext(BlogContext);
useEffect(() => {
blogCtx.getBlogs();
}, []);
console.log(blogCtx);
return <div></div>;
};
export default BlogList;
In the above code when I keep the dependency array empty it works but it keeps giving me a warning. but if I add blogCtx in the dependency array useEffect keeps running infinitely.
I believe it's happening because when getBlog() is called blogCtx is updated, and that causes the component to render again which invokes useEffect again and the same cycle. but I can't seem to find any solution :(
I feel kinda stuck here any help would be appreciated.
getBlog() -> makes a GET request to firebase and gets all the available blogs and updates the blogCtx with the retrieved array of blogs.
Code for `Provider` as requested:
import { useReducer } from "react";
import { getBlogs, createBlog } from "../api/blog-api";
import BlogContext from "./blogs-context";
const defaultState = { blog: [] };
const blogsReducer = (state, action) => {
if (action.type === "FETCH") {
console.log("hi");
return action.data;
}
if (action.type === "CREATE") {
console.log(action.data);
return [...state, action.data];
}
return defaultState;
};
const BlogContextProvider = (props) => {
const [blogList, dispatchBlogAction] = useReducer(
blogsReducer,
defaultState
);
async function fetchBlog() {
let blogs = await getBlogs();
dispatchBlogAction({ type: "FETCH", data: blogs });
}
async function createNewBlog(blogData) {
let response = await createBlog(blogData);
let responseBody = await response.json();
const newBlog = { ...blogData, id: responseBody.name };
if (response.status === 200)
dispatchBlogAction({ type: "CREATE", data: newBlog });
return response;
}
const blogCtx = {
blogs: blogList,
getBlogs: fetchBlog,
addBlog: createNewBlog,
};
return (
<BlogContext.Provider value={blogCtx}>
{props.children}
</BlogContext.Provider>
);
};
export default BlogContextProvider;
Edit: spelling, added code for provider file as requested.