Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 <>...</>;
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda