I have React pages (BlogContent & RelatedBlog),
When a user views blog content, he can see below more blogs for the author. When the user clicks on the article he wants to read, the slug on Url changes but the content does not change until the user refreshes the page, so the user must refresh the page every time he wants to see all related blogs for the author.
I think the reason the blog page require refreshes every time is because useEffect() , but I don't know what is the trick to fix it
Here's my code to page BlogContent:
export const BlogContent = () => {
const { slug } = useParams();
const [data, setData] = useState({ posts: [] });
useEffect(() => {
axiosInstance.get(slug).then((res) => {
setData({ posts: res.data });
});
}, [setData]);
let AuthorBlog = data.posts.author
};
and here for RelatedBlog
export const RelatedBlog = (props) => {
const { AuthorBlog } = props;
const [appState, setAppState] = useState([]);
useEffect(() => {
axiosInstance.get("/").then((res) => {
const allBlogs = res.data;
setAppState(allBlogs);
});
}, [setAppState]);
const filterAuthor = appState.filter((item) => item.author === AuthorBlog) ;
Thanks
As I've written in the comments - adding slug to the dependency array of your useEffect fixed the problem.
Why is that?
Dependency array in useEffect hook is used to rerun the hook when one of these variables changes. In your case, changing the url, changes the slug so the component should load new data.
I would even remove setData from this array, because it doesn't do anything as useState setters don't ever change.
useEffect(() => {
laxiosInstance.get(slug).then((res) => {
setData({ posts: res.data });
});
}, [slug]);