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

196
Visualizações
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 à 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