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

198
Visualizações
I am Getting undefined when trying to get the value of my useParams() in Reactjs

I am experiencing some issues reading the value of my id when using useParams() hook.

I have 4 components:

App.js, Midlocal.js, Blogposts.js and BlogSingle.js

I have the routing set up in App.js

<Route path='/posts/:id' element={<PostSingle />} />

Then I made my Api call in MidLocal.jsx

  const MidLocal = () => {
  const [post, setPost] = useState([]);
  


  async function fetchPosts() {
    const response = await fetch("https://khg.com.ng/wp-json/wp/v2/posts")
    const data = await response.json();

    setPost(data);
      

  };

  useEffect(() => {
    fetchPosts();
  }, []);

Sill in the same MidLocal component, I am using array.map() and passing the data as props to component

<div className="mid__blog__posts">
          {post.map((item) => (
            <BlogPosts
              key={item.id}
              postId = {item.id}
              title={item.title.rendered}
              date={item.date}
              img={item.img}
            />
          ))}
        </div>

This is the BlogPost component. Just a simple functional component where my data could be arranged the way I like it with the react router's Link feature using its TO attribute to point to the single blog page/component

const BlogPosts = ({postId, date, title, img}) => {
  
  return (
    <div className='post__container'>
                    <div className='post__texts'>
                        <small className='md__post__date'>{date}</small>
                        <Link to={`/posts/${postId}`}><h3 className='md__post__title'>{title}<span className='post__url__icon'><BsFillArrowRightCircleFill /></span></h3></Link>
                    </div>
      
                    <img src={img} alt={title} className='post__img'/>
                </div>
  )
}

export default BlogPosts

Then, in the Blog Single component,

const BlogSingle = () => {
  const [content, setContent] = useState([]);

  const {postId} = useParams();

  

  console.log(postId)

  async function fetchPostContent() {
    const response = await fetch(`https://khg.com.ng/wp-json/wp/v2/posts/${postId}`)
    const data = await response.json();

    setContent(data);
      
  };

  useEffect(() => {
    fetchPostContent();
  }, []);

console.log(postId) gives me undefined

and trying to access the value of postId gives me undefined also


<h1>{postId}</h1>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to name the id in the route path accordingly. You named it id and you are trying to access it as postId. Either rename the path in route to contain /posts/:postId or use it as id in your BlogPost: const { id } = useParams();

about 4 years ago · Juan Pablo Isaza Relatório

0

Just destructure id and rename as postId, see the following code for quick reference!

const BlogSingle = () => {
  const [content, setContent] = useState([]);

  const {id: postId} = useParams();

  

  console.log(postId)

  async function fetchPostContent() {
    const response = await fetch(`https://khg.com.ng/wp-json/wp/v2/posts/${postId}`)
    const data = await response.json();

    setContent(data);
      
  };

  useEffect(() => {
    fetchPostContent();
  }, []);

about 4 years ago · Juan Pablo Isaza Relatório

0

let { id: postId } = useParams();
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