Issue
I'm working on Ionic 4 and React and I'm trying to get data from a function to return into the page, but i'm not able to get the data out of the promise.
FYI, i'm using the functional version/pattern of react.
participants.map(participant => {
var paymentStatus = false;
fetchSelectedPaymentEvents(participant, selectedEvent)
.then(data => {
paymentStatus = data;
})
return (
<IonButton color={paymentStatus}>Button<IonButton>
);
});
I've tried using UseState which works somewhat, but I need it to work within the map, but I can't use useState within a React Hook.
Edit: I've tried async/await, but I get the following error when I do: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
Edit:
Here's the code for fetchSelectedPaymentEvents():
function fetchSelectedPaymentEvents(participant_id: any, event_id: any) {
return axios({
url: "URL",
method: "POST",
data: {
"participant_id": participant_id,
"payment_event_id": event_id
}
}).then(response => {
var data = response.data["payment_records"]
if (data === undefined || data.length == 0) {
return "danger"
}
return "success"
})
}
Btw, the purpose of returning "danger" or "success" is not to print exactly the text, but more to be used for styling an Ionic element. Apologies if my code is too misleading. I've edited to make it closer to what I actually need.
Solution
I also think your overall structure of your component is very error prone. Here is how i would attempt to do what you intend to do:
const Component = () => {
const participants = // whereever you get participants from;
return (
<ul>
{participants.map(participant => {
return <Participant participant={participant} />
})
}
</ul>
)
}
const Participant = ({ participant }) => {
const [paymentStatus, setPaymentStatus] = useState("//initialState?");
useEffect(() => {
fetchSelectedPaymentEvents(participant, selectedEvent) // dont where selectedEvent comes from?
.then(data => {
setPaymentStatus(data);
})
}, [participant]}
return (
<li>
{paymentStatus}
</li>
)
}
Hope this makes it a little easier to structure your component
Answered By - jpmarks
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.