Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda