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

324
Vistas
Why my function can't read passed parameters as expectation in React.js?

I use a given postId to fetch all the comments for the post, and I expect to use a saveComments function to set the array of loaded comments into the post id.

So I passed two parameters, postId(should be a number value), and loadedComments(should be an array of comments).

  useEffect(
    () => {
      fetchCommentsForPostId(postId)
      .then( loadedComments => {
        saveComments(postId, loadedComments);
      });
    },
    []
  );

However, when I print the value to check if passed parameters correct. I realize that the first one is good, it's an id for post. But the second one, the comments, it's also an id value. I think it should be an array.

  function saveCommentsForPostId(postId, comments) {

    console.log(postId); // correct id number, eg. 1
    console.log(comments); // incorrect, I think it should be an array of comments, but it is same as postId
    ...
  }

And then, I tried another way. I make my two parameters as an object into calling function.

  useEffect(
    () => {
      fetchCommentsForPostId(postId)
      .then( loadedComments => {
        saveComments({postId, loadedComments});
      });
    },
    []
  );

Now, the postId is still correct. However, the comments is the whole object I passed in. It is like {postId: 1, loadedComments: Array(5)}. How could it be a whole object? I think it should be a pure array.

  function saveCommentsForPostId(postId, comments) {

    console.log(postId); // correct id number, eg. 1
    console.log(comments); // it is an object, eg. {postId: 1, loadedComments: Array(5)}. Why it is an object? I think it should be just an array.

    ...
  }

After tried out a lot of ways, the only working way is I make parameters as an object, and get the array I want use:

comments['loadedComments'] // this is the comment array I actually want

I'm super confused about it. Anyone could explain the logic behind it? Thanks in advance!

*** update

export function fetchCommentsForPostId(postId) {
  return new Promise( (resolve) => {
    // This inserts a 2 second delay so we can easily see a spinner at work
    setTimeout( resolve, 2000);
  })
  .then(
    () => fetch(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`, {
      method: 'GET',
    })
  )
  .catch( () => Promise.reject('networkError') )
  .then( response => {
    if(response.ok) {
      return response.json();
    }
    return Promise.reject('serviceError');
  });
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Ok, not sure what else you are doing but this seems to work:

function fetchCommentsForPostId(postId) {
  return new Promise((resolve) => {
    // This inserts a 2 second delay so we can easily see a spinner at work
    setTimeout(resolve, 2000);
  }).then(() =>
      fetch(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`, {
        method: "GET",
      })
    )
    .catch(() => Promise.reject("networkError"))
    .then((response) => {
      if (response.ok) {
        return response.json();
      }
      return Promise.reject("serviceError");
    });
}

function saveCommentsForPostId(postId, comments) {
  console.log("postId:", postId);
  console.log("comments:", comments);
}

function doStuff(postId) {
  fetchCommentsForPostId(postId).then((loadedComments) => {
    saveCommentsForPostId(postId, loadedComments);
  });
}

doStuff(1);

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