Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

68
Views
State is not gatting update when using setstate in react with hooks

I am facing an issue regarding the setstate. I want to do the following steps:

  1. I m fetching some blogs from the server.
  2. Adding blogs data to blogs state
  3. Filtering a blog that is the same as URL param
  4. Adding that blog to blog state

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 :)

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

  1. 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:
  2. blog doesn't need to be state anyway, since it can be derived from blogs and params; you should just use useMemo then.
  3. There is no need for FixURL to be an inner function. It's cleaner to move it outside the component.
  4. I assume you want a single blog (article) since the state atom is named 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 <>...</>;
}
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs