'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
After 1st Request
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|



