How to use two useParseQuery hook in back4app parse server for implementing one to one chat app - parse-platform

i am trying to implement one to one chat on back4app server, i did not find any blog so going with my instinct.
i have made a class in database which has column from, to and message.
i trying to fetch from and to messages.
for that i using useParseQuery hook. How i can use this hook twice so that i can have message for both 'from' as well 'to'.
const App = () => {
const parseQuery1 = new Parse.Query('Chat_message');
parseQuery1.equalTo('from','amit');
const parseQuery2 = new Parse.Query('Chat_message');
parseQuery2.equalTo('to','amit');
const {
isLive,
isLoading,
isSyncing,
results,
count,
error,
reload
} = useParseQuery(parseQuery2);
console.log(results)
if (isLoading) {
return <ActivityIndicator />;
}
return (
<FlatList
data={results}
renderItem={({ item }) => (
<View
style={{
height: 70,
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>message: {item.get('messages')}</Text>
</View>
)}
/>
);
};
I do not know if my this approach is right, can some one enlighten or give some blog post for chat one to one. thank you good people of stack Overflow.

I used composeQuery.
i had tried with 'and' and that did not work eventually tried with or and that worked.
const parseQuery1 = new Parse.Query('Chat_message');
parseQuery1.equalTo('from','amit');
const parseQuery2 = new Parse.Query('Chat_message');
parseQuery2.equalTo('to','amit');
const composeQuery=Parse.Query.or(parseQuery2,parseQuery1)

Related

"Network interruption occurred. Reconnecting…" , How to potentially automatically reconnect when i minimize or maximize chabot

We have implemented bot framework-webchat to create a bot. Currently, we handle the minimize and maximize with the event passed in component (code shown below) but the challenge occurs when I minimize and then maximize the chatbot I am seeing 'Unable to connect' message and then it flashes away and if after an hour-long later if we minimize and maximize I am getting 'Network interruption occurred, Reconnecting...' How do I keep webchat potentially automatically reconnect when I minimize and maximize Chabot.
MaximizeChatWndow () {
if (this.state.token === null &&
this.state.productService === null) {
return
}
this.setState({
directLine: this.createDirectLine()
}, () => {
this.setState({
minimized: false,
newMessage: false,
userId: 'User_' + Math.random
})
})
this.checkExpandFlag = true
}
The component:
render () {
const {
state: { minimized, store }
} = this 
return (
<Row>
<Col md={12}>
<div>
{minimized ? (
<ChatDon
handleMaximizeButtonClick={this.handleMaximizeButtonClick}
/>
) : (
<ChatWin
handleMinimizeButtonClick={this.handleMinimizeButtonClick}
directLine={this.state.directLine}
userId={this.state.userId}
store={store}
/>
)}
</div>
</Col>
</Row>
)
}
It looks like you creating your directLine object in "MaximizeChatWndow()" which I think is the problem. In "MaximizeChatWndow()", you should be fetching your token and passing that to your web chat component. It is in the web chat component that you should use the token to call createDirectLine().
It appears that there have been various updates to the 06.recomposing-us/a.minimizable-web-chat sample. (The docs also look like they are out of date and no longer match the code). However, if comparing to the available sample code, you will want to do something like the following. Please look at the full code in the above link as I am only including the most relevant parts here.
When I tested, I had no issues with the conversation resetting or the network disconnecting/reconnecting.
MinimizableWebChat.js
import WebChat from './WebChat';
const MinimizableWebChat = () => {
[...]
const [token, setToken] = useState();
const handleFetchToken = useCallback(async () => {
if (!token) {
const res = await fetch('http://localhost:3500/directline/token', { method: 'POST' });
const { token } = await res.json();
setToken(token);
}
}, [setToken, token]);
[...]
return (
[...]
<WebChat
className="react-web-chat"
onFetchToken={handleFetchToken}
store={store}
styleSet={styleSet}
token={token}
/>
)
WebChat.js
const WebChat = ({ className, onFetchToken, store, token }) => {
const directLine = useMemo(() => createDirectLine({ token }), [token]);
[...]
useEffect(() => {
onFetchToken();
}, [onFetchToken]);
return token ? (
<ReactWebChat ...
);
};
Hope of help!

react hooks invalid call hooks

Hello i'm trying to load a style into my ui stuff but i'm having trouble doing that
const useStyles = makeStyles(loginPage)
const classes = useStyles();
const renderTextField = ({
label,
input,
meta: { touched, invalid, error },
...custom
}) => (
<TextField
label={label}
placeholder={label}
variant="outlined"
InputLabelProps={{
classes: {
root: classes.label,
focused: classes.focusedLabel,
error: classes.erroredLabel
}
}}
InputProps={{
classes: {
root: classes.cssOutlinedInput,
focused: classes.cssFocused,
notchedOutline: classes.notchedOutline,
},
startAdornment: (
<InputAdornment position="start">
<PersonSharpIcon style={{ fontSize: 25 , color: 'rgba(20, 176, 12,0.9)' }} />
</InputAdornment>
)
}}
error={touched && invalid}
helperText={touched && error}
{...input}
{...custom}
/>
)
error:
Error: Invalid hook call. Hooks can only be called inside of the body
of a function component.
Could someone help me how I would solve this?
It's exactly as the error message says. You need to move your hook inside the body of your function component.
React considers every function starting with 'use' as a hook. So in your case it's useStyles(). React also expects such functions to be called only from inside of the body of function components and only from the root of it (so nesting it inside loops or conditional statements is a big no - you can read about it here). Your function component is renderTextField, so as you can see you're calling useStyles() OUTSIDE of renderTextField's body.
Structuring it something like this should help:
const useStyles = makeStyles(loginPage);
const RenderTextField = ({
label,
input,
meta: { touched, invalid, error },
...custom
}) => {
const classes = useStyles(); // <-- Move it here
return (
<TextField
label={label}
...
>
...
</TextField>
);
}

Custom web-chat background image

I am trying to make my own chatbot but am unsure of how to change the background image to my own jpg.
I have tried to place the code in the <body> and inside the styleOptions but none of my methods work.
Below is my html file:
<body style = "background-image: url('CorpBotOrchestrator/Images/whatsapp.jpg');">
<div id="webchat" role="main">Loading...</div>
<script>
styleOptions: {
bubbleFromUserBackground: 'LightBlue',
hideUploadButton: true,
botAvatarImage: 'https://learn.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
//make the speech bubbles round
bubbleBorderRadius: 20,
bubbleFromUserBorderRadius: 20,
}
}, document.getElementById('webchat'));
})().catch(err => console.error(err));
</script>
</body>
Thank you in advance!
You will want to instantiate your web chat in the following way to change the background image of the activities window. Be aware that, in the BotFramework-WebChat styleSet object, there is activity which represents the individual messages, cards, etc., that are sent, and there is activities which represents the window of scrolling messages. It is the latter we will be working with.
Also, be aware, that because you are directly specifying a DOM element and property, albeit via web chat, should some aspect of web chat receive an update that changes the element or property used, this can cause a breaking change for you. Additionally, you will need to pass all the property values necessary as, generally, this strips all default values from the webchat element you are working with.
const styleSet = createStyleSet ( {
bubbleBackground: 'blue',
bubbleFromUserBackground: 'red',
bubbleBorderRadius: 18,
bubbleFromUserBorderRadius: 18,
} );
styleSet.activities = {
...styleSet.activities,
backgroundImage: "url('<someUrlLink>')";
}
window.WebChat.renderWebChat( {
directLine: [...],
styleSet
});
Hope of help!
EDIT
styleOptions can actually be passed in using the spread operator into styleSet. In this way, you can continue to use the ease of styleOptions for customizing and largely remain within best practices of Web Chat.
const styleOptions = {
bubbleBackground: 'blue',
bubbleFromUserBackground: 'red',
bubbleBorderRadius: 18,
bubbleFromUserBorderRadius: 18
}
const styleSet = createStyleSet ( {
...styleOptions,
} );
styleSet.activities = {
...styleSet.activities,
backgroundImage: "url('<someUrlLink>')";
}
window.WebChat.renderWebChat( {
directLine: [...],
styleSet
});

React render image from prop

I am trying to pass an image url to the children and then require it as follows:
import React, {Component} from 'react';
let color = require('../../css/colors.js');
let defaultStyle = {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexBasis: 'calc(50% - 40px)',
flexDirection: 'column',
margin: '20px',
backgroundColor: color.blueCard
}
class Card extends Component {
render() {
const imgUrl = require(this.props.background);
return (<div style={{
...defaultStyle
}}>
<img src={imgUrl} alt="img"/>
</div>);
}
}
export default Card;
this.props.background looks something like this: "../../img/album1.jpg"
When im starting the React App i get the following error message on const imgUrl = require(this.props.background);:
Error: Cannot find module "."
webpackMissingModule
The React App was created using create-react-app. My guess is that webpack cant parse the resource file.
**Parent Component**
<InputSection ref="inputS" ImD={this.getData} imageUri={require(this.state.imageurl)} />
**Child Component**
<img ref="image" src={this.props.imageUri} />
try this, I think it will work.
Does not need the require in this case, You can simply get the props which you're passing from the Parent component.
for ex :
<Card background={your_value}/>
then in Card component
const imgUrl = this.props.background;

How to show and hide activityindicator from actions in react native redux?

I want to show progress/activityindicator whenever I make an api call from my app, But I can't find the correct solution for this. I can show the activityindicator but I can't hide it from view. Here is my code:
StatusModal.js
constructor(props) {
super(props)
// set state with passed in props
this.state = {
message: props.error,
hide: props.hide,
animating: props.animating
}
}
render() {
if(this.state.animating){
return(
<ActivityIndicator
animating={true}
size="small"
/>
)
}else{
return(
<View>
</View>
)
}
}
and here is how I change the animating state
//show activity
Actions.statusModal({animating: true})
//hide activity
Actions.statusModal({animating: false})
and here is my scene structure:
<Scene key="modal" component={Modal} >
<Scene key="root">
<Scene key='login' component={Login} title='Login Page' hideNavBar={true} />
</Scene>
<Scene key="statusModal" component={StatusModal} />
</Scene>
How can I hide the activity indicator from actions?
It's pretty common thing for applications to handle loading.
The simplest way to handle it is create a separate reducer for this.
E.g.:
function appStateReducer(state = { loading: false }, action) {
switch(action.type) {
case "SET_LOADING":
return { loading: action.payload };
default:
return { loading: false };
}
}
...
const rootReducer = combineReducer(
...otherReducers,
app: appStateReducer
);
...
Later you can use it in your components.
...
const mapStateToProps = (state) => ({
loading: state.app.loading,
});
#connect(mapStateToProps)
class MyScene extends Component {
...
render() {
const { loading } = this.props;
if (loading) {
return (
);
}
return ;
}
Dispatch action SET_LOADING in the start of query with true and dispatch SET_LOADING with false in the end or in case of error.
But one single state for handling loading isn't enough for big application. For example: you need to handle parallel queries to API and to show loader for every single query. Then you'll need such fields in other reducers.
By the way, you'll definitely meet the issue with async flow. I would recommend such middlewares as redux-thunk, redux-saga and redux-observable.
My favourite one is redux-saga. It's a very powerful way to control your async flow and all other side effects in your application.
I hope it helps.

Resources