- The user is not able to obtain due to the
dispatch(settoken(..)) (called in AppClient)not being called before thegetScenario()function. To fix this issue, I have made the dependency on the token by using theuseSelectorhook and wrapped thegetScenario()function within a conditional statement to ensure that it is only called when the token is available. Once the scenarios are fetched, they are transformed and set as options for further use.
const token = useSelector((state) => state.data.token);
useEffect(() => {
if (token) {
getScenario()
.then(({ scenarios }) => {
// console.log(scenarios);
const transformedScenarios = scenarios.map(option => ({
scenario: option.name,
description: option.categories.name,
value: option._id
}));
setOptions(transformedScenarios);
setSelectedOption(transformedScenarios[0]?.value || null);
})
.catch((error) => {
console.error('Failed to fetch scenario options:', error);
});
}
}, [token]);
2.
const [selectedValue, setSelectedValue] = useState(value || options[0]?.value || null);
For code above there is a possibility that the options array might be empty when trying to read the selected option, as it's from useState of upper component. To handle this scenario correctly, I have implemented a more robust approach using the useState hook. The selectedValue state is initially set to the provided value, and if it is not available, it falls back to the first option's value from the options array. In case both value and the first option are unavailable, selectedValue is set to null.
right way to do it
useEffect(() => { if (value) { setSelectedValue(value); } else if (options[0]?.value) { setSelectedValue(options[0]?.value); } else { setSelectedValue(null); } }, [value, options]);
3. When we await <function> we need to make sure we return the promise at that funciton, otherwise it will not wait for the completion of reloadScenarios before return
like
await reloadScenarios
const reloadScenarios = () => {
if (token) {
return getScenario()
.then(({ scenarios }) => {
const transformedScenarios = scenarios.map(option => ({
scenario: option.name,
description: option.categories.name,
value: option._id
}));
setOptions(transformedScenarios);
// setSelectedOption(transformedScenarios[0]?.value || null);
})
.catch((error) => {
console.error('Failed to fetch scenario options:', error);
});
}
};
No comments:
Post a Comment