How to add values to channelData of message using hooks - botframework

I am using the Customization Plain UI sample and need to add custom data to the channelData. What is the best way to accomplish this when using this sample?

You can add a store middleware to the Customization Plain UI sample that adds custom channel data by passing a custom store as a prop to the Composer component. For more details, take a look at the Piggyback Data Web Chat Sample.
export default () => {
...
const store = useMemo(() => createStore({}, () => next => action => {
if (action.type === 'DIRECT_LINE/POST_ACTIVITY') {
action = simpleUpdateIn(
action,
['payload', 'activity', 'channelData', 'email'],
() => 'johndoe#example.com'
);
}
return next(action);
}), []);
...
return (
<React.Fragment>
...
{!!directLine && (
<Components.Composer directLine={directLine} store={store}>
<PlainWebChat />
</Components.Composer>
)}
</React.Fragment>
);
};

Related

Dispatch actions from a custom hook using useQuery

I'm trying to write a custom hook that uses useQuery from react-query. The custom hook takes in the id of an employee and fetches some data and returns it to the consuming component. I want to be able to dispatch a redux action to show a loading indicator or show an error message if it fails. Here is my custom hook.
export default function useEmployee(id) {
const initial = {
name: '',
address: '',
}
const query = useQuery(['fetchEmployee', id], () => getEmployee(id), {
initialData: initial,
onSettled: () => dispatch(clearWaiting()),
onError: (err) => dispatch(showError(err)),
})
if (query.isFetching || query.isLoading) {
dispatch(setWaiting())
}
return query.data
}
When I refresh the page, I get this error in the browser's console and I'm not sure how to fix this error?
Warning: Cannot update a component (`WaitIndicator`) while rendering a different component (`About`).
To locate the bad setState() call inside `About`, follow the stack trace as described in
The issue is likely with dispatching the setWaiting action outside any component lifecycle, i.e. useEffect. Move the dispatch logic into a useEffect hook with appropriate dependency.
Example:
export default function useEmployee(id) {
const initial = {
name: '',
address: '',
};
const { data, isFetching, isLoading } = useQuery(['fetchEmployee', id], () => getEmployee(id), {
initialData: initial,
onSettled: () => dispatch(clearWaiting()),
onError: (err) => dispatch(showError(err)),
});
useEffect(() => {
if (isFetching || isLoading) {
dispatch(setWaiting());
}
}, [isFetching, isLoading]);
return data;
}

Get vuex store state after dispatching an action

I'm creating a chat application in Laravel 6 + Vue + Vuex. I want make a call to vuex store and get a state after a dispatch actions is complete and then I want to do some processing on that state in my vue component.
In ChatWindow component
mounted: function () {
this.$store.dispatch('setContacts').then(() => {
console.log('dispatch called')
// I want to call the getter here and set one of the data property
});
}
action.js
setContacts: (context) => {
axios.post('/users').then(response => {
let users = response.data;
// consoled for testing
console.log(users);
context.commit('setContacts', users);
});
}
mutators.js
setContacts: (state, users) => {
state.contacts = users;
},
Please see the screenshot below. The then method of dispatch is running before setContacts in action.js.
I need to call the getter after completing dispatch action. (which will effectively set the contacts state). Then, I want to get the contacts through getContacts getter like this.
getters.js
getContacts: (state) => {
return state.contacts;
}
I also tried calling computed property in then in mounted and it didn't work. Also, shouldn't 'dispatch called' in mounted run after console.log of setContacts in action.js as it is in then method? Thanks!
Maybe you could wrap axios call inside another promise.
return new Promise((resolve, reject) => {
axios.post('/users')
.then(response => {
let users = response.data;
// consoled for testing
console.log(users);
context.commit('setContacts', users);
resolve('Success')
})
.catch(error => {
reject(error)
})
})
And then
this.$store.dispatch('setContacts')
.then(() => {
console.log('dispatch called')
console.log('getter ', this.$store.getters.contacts)
});
Let me know what happens. It was working for a small demo that I tried.

Invalid hook call. React hooks

error:
Error: Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons
Hello I am trying to use useDispatch in my action but it is generating this error from invalid hoook
I can't solve it
can anybody help me?
my action
import {FETCH_FAIL,FETCH_LOADING,FETCH_SUCESS} from './actionType';
import api from '../../../services/api';
import { useDispatch } from "react-redux";
const FetchSucess = data => (console.log(data),{
type:FETCH_SUCESS,
data
});
const FetchFailed = error => ({
type:FETCH_FAIL,
error
});
const isLoadingFetch = () => ({type: FETCH_LOADING})
export default function AllProducts () {
const dispatch = useDispatch()
dispatch(isLoadingFetch());
// fetching data
api.get('/products')
.then( response => { dispatch(FetchSucess(response.data))})
.catch( err => { dispatch(FetchFailed(err.message));});
}
my component
import React, { useState, useEffect } from 'react';
export default function Cards() {
useEffect(() => {
// This will be invoked only once.
getAllProducts();
}, []);
const classes = useStyles();
const classes2 = useStyles2();
const products = useSelector(state => state.data.filteredProducts);
return (
<div className="App">
<Container maxWidth="md" className={classes.root}>
<Grid container md={4} spacing={1} ></Grid>
<Grid container md={8} spacing={1} alignItems={"center"}>
{products.map(product => (
<Grid item lg={4} md={4} sm={12} xs={12}>
<Card className={classes2.card}>
<CardMedia
className={classes2.media}
image={
"https://www.theclutch.com.br/wp-content/uploads/2019/11/skins-csgo-neymar.jpg"
}
/>
<CardContent className={classes2.content}>
<Typography
className={classes2.name}
variant={"h6"}
gutterBottom
>
{product.name}
</Typography>
<Typography
className={classes2.price}
variant={"h1"}
>
{util.formatCurrency(product.price)}
</Typography>
</CardContent>
</Card>
</Grid>
))}
</Grid>
</Container>
</div>
);
}
Based on this comment above:
All product is my action
If AllProducts is a Redux action that needs to perform an async operation and dispatch other actions in response to that operation, there's a convention available by which Redux will pass dispatch as a function argument. The action just needs to return a function which accepts that argument. For example:
export default function AllProducts () {
return function(dispatch) {
dispatch(isLoadingFetch());
// fetching data
api.get('/products')
.then( response => { dispatch(FetchSucess(response.data))})
.catch( err => { dispatch(FetchFailed(err.message));});
}
}
There's no need to use the hook, that's only necessary within React Function Components or within other hooks (which themselves are used within React Function Components).

Can you render user message before it appears in webchat?

For MS Botframework webchat, Is there a way to intercept user message before being rendered in webchat and change it?
This is easy to accomplish using the createStore() method.
In the web chat script located in your page, create the store using the above method. In it, match the action.type to 'WEB_CHAT/SEND_MESSAGE'. This will capture every message that is passed thru the web chat component before it is displayed.
Be aware, this altered text (or whatever value you are changing) is what is sent to the bot. action is the root object. action.payload, effectively, represents the activity. This is where you will find the text value, etc.
Within the if statement, perform whatever change you are looking to make, then return the action object.
Lastly, include the store object within the renderWebChat component. This should set you up.
In the example below, I am appending text to the text field altering it before it is rendered and displayed.
<script>
( async function () {
const res = await fetch( 'http://somesite/directline/token', { method: 'POST' } );
const { token } = await res.json();
// We are using a customized store to add hooks to connect event
const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => action => {
if ( action.type === 'WEB_CHAT/SEND_MESSAGE' ) {
action.payload.text = action.payload.text + ' (Hello from behind the curtain)'
}
return next( action );
} );
window.WebChat.renderWebChat( {
directLine: window.WebChat.createDirectLine( { token } ),
userID: 'user123',
username: 'johndoe',
botAvatarInitials: 'BB',
userAvatarInitials: 'JD',
store
}, document.getElementById( 'webchat' ) );
document.querySelector( '#webchat > *' ).focus();
} )().catch( err => console.error( err ) );
</script>
Hope of help!

React Redux thunk - Chaining dispatches

Currently i'm building an application that is heavily dependant on API calls. The api calls are done within Redux actions with Thunk middleware like so:
export const brand_fetchAll = () => {
return dispatch => {
fetch(apiURL+'brand')
.then(response => {return response.json();})
.then(content => {
dispatch({
type: 'BRAND_STORE_ALL',
content
})
})
.catch(error => console.log(error))
}}
In my component, i'm first fetching the data through separate actions. After that i'm opening up an editor:
// A component method
editModeOn(){
// Fetch data
this.props.dispatch(campaign_fetchAll());
this.props.dispatch(brand_fetchAll());
// Open editor
this.props.dispatch(page_editModeOn());
}
Right now the editor opens before the api calls have completed, so no data is being shown. It's possible to chain the dispatches within the actions, but i want to keep the modularity, so i don't have to create hundreds of custom API calls. Ideally what i want is to chain them using something like promises:
// A component method
editModeOn(){
this.props.dispatch(campaign_fetchAll().then(brand_fetchAll()).then(page_editModeOn());
}
Unfortunately i didn't yet get that to work. I hope someone can help me out. If you need more information i'm happy to hand it over. Better ideas are also very welcome :)
Thanks in advance!
Would a callback function be an option for you?
So update your code to be;
export const brand_fetchAll = (callback) => {
return dispatch => {
fetch(apiURL+'brand')
.then(response => {return response.json();})
.then(content => {
dispatch({
type: 'BRAND_STORE_ALL',
content
});
callback();
})
.catch(error => console.log(error))
}}
// A component method
editModeOn(){
// Fetch data
this.props.dispatch(campaign_fetchAll());
this.props.dispatch(brand_fetchAll(() => {
// Open editor
this.props.dispatch(page_editModeOn());
}));
}
You are chaining the callback onto the end of the api call success, however, you are not tightly coupling what it is as you are passing this in depending on the usage.

Resources