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

200
Vistas
How to make state of each react component as independent?

I am creating a card that shows questions and it makes a GET request to my server and shows the answer to the asked question

The CODE Below of the component shows how the API request is made

  const ChatBoxIItem = ({ message }) => {
  const [ans, setAns] = useState(null);

  getAns(message);
  async function getAns(message) {
    if (!message) {
      return;
    }

    st_chat_asked_question = message;

    let param = {
      question: message,
    };
    param = JSON.stringify(param);
    let url;
    let res_data;
    try {
      console.log(param);
      let curr_data = new Date();

      url = `${process.env.REACT_APP_API_URL}/student/question_answer`;
      res_data = await send_xhr.post(param, url, "application/json");
      res_data = JSON.parse(res_data);

      curr_data = new Date();
      let time = curr_data.toLocaleTimeString();

      if (
        res_data.answers &&
        res_data.answers[0] &&
        res_data.answers[0].score > 0
      ) {
        st_chat_response_data = res_data;
        console.log(res_data);
        setAns(res_data.answers[0].answer);
      } else {
      }
    } catch (e) {

      display_mess("something went wrong", "error", 5000);
      window.scrollTo(0, 100);
      console.log(e);
      return;

    }
  }

  return (
    <div className='st-cs-chat-item'>
      <div className='st-cs-chat-item-header'>
        <p className='st-cs-chat-item-question'>{message}</p>
        <p>{ans ? ans : <p>Searching For Answer</p>}</p>
      </div>
    </div>
  );
};

It's working fine but only for the first component when 2 or more request is made it changes the value of the 1st state also to "Searching for ans"

When 1st request is made

enter image description here

After 1st Request

enter image description here

When 2nd request is made (States of both components changes) How to fix this issue I don't want to change the states of previous components Need each of them as independent

enter image description here

about 4 years ago · Juan Pablo Isaza
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