I am facing an issue regarding the setstate. I want to do the following steps:
problem is coming at stape 4 when I am trying to add that particular blog to the blog state. When I am logging both states, the blog state is coming as empty array [].
function BlogDetail(props) {
const [blog, setBlog] = useState([]);
const [blogs, setBlogs] = useState([]);
let param = useParams();
// Fetch blogs from server
const getBlogs = () => {
axios
.get("/blog/all_blog/")
.then((res) => {
setBlogs(res.data);
console.log(res.data);
})
.catch((err) => console.log(err));
};
const getBlog = () => {
const FixURL = (url) =>
url
.replace(/[^a-zA-Z ]/g, "")
.replace(/\s+/g, "-")
.toLowerCase();
setBlog(blogs.filter((artical) => FixURL(artical.title) === param.id));
};
useEffect(() => {
getBlogs();
getBlog();
}, []);
console.log(blog);
console.log(blogs);
return <>...</>;
}
I also tried to warp this setBlog into callback function but does work for me, not gatting why the blog state is gating updated.
Thanks in Advance :)
getBlog()
runs before getBlogs()
's fetch finishes, so there are no blogs
to filter over. The contents of getBlog()
could be moved to the .then()
in getBlogs()
, but that's not a good idea:blog
doesn't need to be state anyway, since it can be derived from blogs
and params; you should just use useMemo
then.FixURL
to be an inner function. It's cleaner to move it outside the component.blog
, so I changed .filter
to find
.const FixURL = (url) =>
url
.replace(/[^a-zA-Z ]/g, "")
.replace(/\s+/g, "-")
.toLowerCase();
function BlogDetail(props) {
const [blogs, setBlogs] = useState();
const { id } = useParams();
useEffect(() => {
axios.get("/blog/all_blog/").then(({ data }) => setBlogs(data));
}, []);
const blog = React.useMemo(() => (blogs || []).find((article) => FixURL(article.title) === id));
console.log(blog);
console.log(blogs);
return <>...</>;
}