I have a react page where I show all FAQs items in a list within a javascript map loop. There are two buttons yes or no. Users can vote an answer yes or no. So whenever the user clicks the buttons a loading indicator will show.
Faqs Page:
<>
{
faqs.map((faq) => (
<Faq key={faq.id} faq={faq} />
))
}
</>
Faq component:
interface IProps {
faq: IFaq;
}
const FaqVoteSection: React.FC<IProps> = (props) => {
const { faq } = props;
const dispatch = useDispatch();
const { faqVoteLoading } = useSelector((state: AppState) => state.user);
const [loadingState, setLoadingState] = useState<
'yesvote-loading' | 'novote-loading' | 'not-loading'
>('not-loading');
const onVoteSubmit = async (vote: boolean) => {
if (faq) {
dispatch(
faqVoteApiAction({
faq_id: faq.id,
vote,
})
);
setLoadingState('not-loading');
}
};
const onYesVotePress = () => {
setLoadingState('yesvote-loading');
onVoteSubmit(true);
};
const onNoVotePress = async () => {
setLoadingState('novote-loading');
await onVoteSubmit(false);
};
return (
<FlexContainer>
<SolidButton
type={faq.vote === 'yes' ? 'primary' : 'default'}
size="small"
onClick={onYesVotePress}
loading={loadingState === 'yesvote-loading' && faqVoteLoading}
>
Yes
</SolidButton>
<Gap />
<SolidButton
size="small"
type={faq.vote === 'no' ? 'primary' : 'default'}
onClick={onNoVotePress}
loading={loadingState === 'novote-loading' && faqVoteLoading}
>
No
</SolidButton>
</FlexContainer>
);
};
Now when I click a vote button I want to show the loading only for that item. But the loading shows every item in the list. I think it's because of the map loop.