im having trouble displaying message that i post to api through hendleSubmit function. Message is sent and added to array, but it is not displayed immediately, only shows once i reload page. Can someone help me with this?
here is my code:
export const ConversationForm = () => {
const { isLoading, data={} } = useQuery(['conversationForm'], () => conversationMessageService.getConversationMessages());
}
declaration of the component and getting data from api in 'data' array
<Grid container className={classes.conversation}>
<SadStates
states={[
{
when: isLoading,
render: <Loader/>
}
]}>
{data.items===undefined?
<img src={emptyChatIcon} alt={''}/>:
<ScrollToBottom mode='bottom' className={classes.scrollBottom}>
{data.items.map((message) => {
return (
<ConversationMessage
message={message}
key={message.id}
customerName={customerName}
userName={userName}/>
);
})}
</ScrollToBottom>
}
</SadStates>
</Grid>
Calling child component for printing message by message
<Formik
initialValues={{
userPhone: userPhone,
customerPhone: customerPhone,
conversationMessageSender: conversationMessageSender,
body: '',
conversationMessageType: 1}}
onSubmit={handleSubmit}>
{({}) => (
<Form>
<Grid container>
<Grid item>
<ConversationInputField inputName='body'/>
</Grid>
<Grid item>
<button type='submit'>
<Grid item>
<img src={sendIcon} alt={''}/>
</Grid>
</button>
</Grid>
</Grid>
</Form>
)}
</Formik>
form where i call post method on submit
const handleSubmit = async( values, { setSubmitting }) => {
try {
await conversationMessageService.createConversatonMessage(values);
values.body='';
setSubmitting(false);
} catch (error) {
console.log(error);
}
};
handleSubmit functon
I don't see anywhere in your code refetching submitted data. How should your front-end know that you have changed X to Y on your backend?
Either refetch it once you submitted and refresh local state that holds your data and/or do an optimistic update on your local state while the correct value is being fetched from your backend.
React query is a really great tool for exactly this. Mutating data allows you to also cancel previous queries (starting an automatic refresh) and also doing optimistic updates, where you predict your what your state is going to look like, in case the data you are manipulating takes a longer time to load/is very complex in nature in order to avoid making the user wait.