Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!