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

302
Visualizações
How to fetch data using functional components with hooks in reactjs

I am working with nextjs and i am trying to use "functional component" with "hooks" for fetch data using "axios",but i am getting following error "AxiosError: Request failed with status code 404" Here is my code

import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";

const Post = () => {
  let params = useParams();
  const [post, setPost] = useState(null)

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(post => {
        setPost(post)
      });
  }, [])
  
  return (
    <div>
      {post !== null ? (
        <div>
          <h4>{res.data.title}</h4>
          <p>{res.data.body}</p>
        </div>
      ) : (
        <div>Loading post...</div>
      )}
    </div>
  )
}
export default Post
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Part where you are making request looks fine, but one that seems wrong is render part where you are trying to display res.data.title and res.data.body, but the problem is that title and body do not exist on response from /posts endpoint - this endpoint will return you array of random posts, meaning that res.data is an array which you can use in order to traverse and display posts.

Also I suggest you to rewrite .then part to:

.then(response=> {
    setPosts(response.data)
  })

As you can see I named input parameter as response, and not post(as you did), because this input parameter represents axios response which is wrapper around the data retrieved from endpoint. You should just store response.data inside inner state, no need to hold axios-specific. Also you should rewrite [post, setPost] to [posts, setPosts], to plural, because this endpoint returns list of posts, and not just one single post.

UPDATED

Rewrite to something like this:

 import { useState, useEffect } from "react";
 import { useParams } from "react-router-dom";
 import axios from "axios";     

 const Post = () => {
  let params = useParams();
  const [posts, setPosts] = useState(null)

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        setPosts(response.data)
      });
  }, [])
  
  return (
    <div>
      {posts !== null ? 
        posts.map(post => (
          <div key={post.id}>
            <h4>{post.title}</h4>
            <p>{post.body}</p>
          </div>
        ))
       : (
        <div>Loading posts...</div>
      )}
    </div>
  )
}
export default Post
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