I'm using react-simple-chatbot in a React application and encountering an issue where dynamically updating the chatbot's options doesn't reflect the changes on the UI, even though the state is correctly updated.
Problem:
I have a list of options (availableOptions) that I want to dynamically filter as the user selects them. I'm using useState to manage availableOptions and steps within my chatbot component. When a user selects an option, I filter the availableOptions state and update the steps array to reflect the new options.
const [availableOptions, setAvailableOptions] = useState([
// Initial options
]);
const handleSelection = (option) => {
const updatedOptions = availableOptions.filter((opt) => opt.value !== option);
setAvailableOptions(updatedOptions);
};
const [steps, setSteps] = useState([
{
id: "2",
options: availableOptions.map((option) => ({
value: option.value,
label: option.label,
trigger: option.trigger,
})),
},
// Other steps
]);
useEffect(() => {
const updatedSteps = steps.map((step) => {
if (step.id === "2") {
return {
...step,
options: availableOptions.map((option) => ({
value: option.value,
label: option.label,
trigger: option.trigger,
})),
};
}
return step;
});
setSteps(updatedSteps);
}, [availableOptions]);
I'm using an AsyncMessage component to handle asynchronous data fetching and update the availableOptions state.
const AsyncMessage = ({ option, triggerNextStep, availableOptions, setAvailableOptions }) => {
// ... data fetching and state update logic
const handleSelectionPromise = (option) => {
return new Promise((resolve) => {
const updatedOptions = availableOptions.filter((opt) => opt.value !== option);
setAvailableOptions(updatedOptions);
resolve();
});
};
useEffect(() => {
const fetchMessage = async () => {
// ... fetch data
await handleSelectionPromise(option);
setTimeout(() => triggerNextStep({ value: responseMessage }), 1000);
};
fetchMessage();
}, [option, triggerNextStep, availableOptions, setAvailableOptions]);
};
- Even though availableOptions is correctly updated (verified via console.log), the react-simple-chatbot UI still displays the old options.
- The options are not being removed from the chatbot UI, despite the updated options being passed to the chatbot.
- I attempted to use a key to force a re-render of the Chatbot, but that caused the chat history to be reset.
- I attempted to use the input and handleEnd props, but still the UI does not update.