Subscription component with GraphQL Apollo Client - graphql

I have an application with one subscription already using subscribeToMore
Query Component:
<Query query={GET_MESSAGES}>
{({ data, subscribeToMore }) => {
return (
<MessageList
messages={data.allMessages}
subscribeToMore={subscribeToMore}/>
);
}}
</Query>
That query loads a list of messages where as far as I know we attach the subscriber in the ComponentDidMount so whenever I add a new element into my list inside the Query, my subscription will listen to the subscription and do whatever I want (in this case add the new message into my current list of messages).
List of Messages Component:
export default class MessageList extends React.Component {
componentDidMount() {
this.props.subscribeToMore({
document: MESSAGE_CREATED,
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
return {
allMessages: [
subscriptionData.data.messageCreated,
...prev.allMessages
],
};
},
});
}
render() {
return (
<div>
{this.props.messages.map(message => (
<MessageElement key={message.id}
message={message}/>
))}
</div>
);
}}
I would like to add another subscription so if I edit my message the information is updated in real time. In order to achieve that I have created the following component using Subscription
Message component (where I would like to add another subscription based on an updated message)
export default class MessageElement extends Component{
componentDidMount() {
this.messageUpdatedSubscription();
}
messageUpdatedSubscription = () => (
<Subscription
subscription={MESSAGE_UPDATED}>
{({ data: { messageUpdated } }) => (
console.log('Do smthg???',messageUpdated)
)}
</Subscription>
);
render(){
return(
<Mutation mutation={UPDATE_MESSAGE} key={this.props.message.id}>
{updateMessage => (
<div>
<div>{this.props.message.text}</div>
<div>
<Star active={this.props.message.isFavorite}
onClick={() => { updateMessage({ variables: {
id: this.props.message.id,
text:this.props.message.text,
isFavorite:!this.props.message.isFavorite } });
}}/>
</div>
</div>
)}
</Mutation>);
}}
My subscriptions on the server are working as I already have the subscription for MESSAGE_CREATED on the Query working correctly and I have tested that on the server my subscription for the MESSAGE_UPDATED is triggered. However, I cannot figure out why the UI is not displaying or console.log anything as if it is not listening to the subscription.
Can I achieve this with a subscription component or with a subscribeToMore?
Thanks in advance

The subscription component cannot be initiated in ComponentDidMount. It has to reside in a render() lifecycle method. It's parameter can be used in ComponentDidMount, but not the component.
I can think of 3 possible solutions:
1) You could try to put the Subscription method in your render method. You would just need to nest this inside or outside of your Mutation component.
2) You could initiate the Subscription Component in this component's parent and pass its parameter (messageUpdate) down to the component MessageElement. You could then use messageUpdate off of props in ComponentDidMount.
3) You could use Apollo's higher order component. You could then access messageUpdate in props. (Disclaimer - I have not tried this before).
I hope this helps!

Based on the suggestion of #cory-mcaboy I nested my subscription into the mutation.
I also found out that as I had a list of messages and I just wanted to trigger the subscription based on the message I am updating and not the entire list; I had to modified my subscription on the backend and on the front end in the following way:
Server schema
const typeDefs = gql` type Subscription {
messageUpdated(id: Int!): Message}`;
Server resolver
Subscription: {
messageUpdated: {
subscribe: withFilter(
() => pubsub.asyncIterator([MESSAGE_UPDATED]),
(payload, variables) => {
return payload.messageUpdated.id === variables.id;
},
),
},
}
Client component
const MESSAGE_UPDATED = gql` subscription messageUpdated($id: Int!){
messageUpdated(id:$id)
{
id
text
isFavorite
}}`;
export default class MessageElement extends Component{
render(){
return(<Mutation mutation={UPDATE_MESSAGE} key={this.props.message.id}>
{updateMessage => (
<div>
<div>{this.props.message.text}</div>
<Subscription subscription={MESSAGE_UPDATED}
variables={{ id: this.props.message.id }}>
{() => {
return <Star active={this.props.message.isFavorite}
onClick={() => { updateMessage({ variables: {
id: this.props.message.id,
text: this.props.message.text,
isFavorite: !this.props.message.isFavorite } });}}/>
}}
</Subscription>
</div>
)}
</Mutation>
);
}}
You can see the code in the following repo: back-end itr-apollo-server, front-end itr-apollo-client

I saw a lot of users struggling to use useSubscription in Class Component as Apollo deprecated the Subscription component in the newer version. So, I decided to create quick gist of how to use it.
https://gist.github.com/syedadeel2/a9ec6ff0d9efade2b83d027f32ce21dc

Related

What is a good practice for setting up a redux-backed form in Twilio Flex that keeps state for each reservation?

I am building a React form in the CRM pane of Flex which will POST data to an external service when the agent fills out the form and hits a submit button. Using the example code from create-flex-plugin from Plugin Builder v3, I have successfully persisted the data from a form field in redux. However, as an agent in Flex, if I have multiple reservations open, when I toggle between them they use the same data. How do I design my form so that an agent can enter data in the form for different reservations and they are kept separately?
I am relatively new to Flex, React and Redux, and not sure if there is anything Flex-specific about what I need to do, especially when handling multiple concurrent reservations. I've thought of keeping a Map keyed by reservationId or taskId in redux, but it's not clear how I'd pass the taskId into the reducer. I am also not sure if other tools like redux-form will play nice with Flex's design.
Being pointed in the right direction or getting some sample code would be a great help.
My current implementation, which persists a field called 'subcategory', looks like this:
HrmFormState.js
const UPDATE_FORM = 'UPDATE_FORM';
const initialState = {
subcategory: 'my category',
};
export class Actions {
static updateForm = (e) => ({ type: UPDATE_FORM, text: e.target.value });
}
export function reduce(state = initialState, action) {
switch (action.type) {
case UPDATE_FORM: {
return {
...state,
subcategory: action.text,
};
}
default:
return state;
}
}
HrmForm.Container.js
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Actions } from '../../states/HrmFormState';
import HrmForm from './HrmForm';
const mapStateToProps = (state) => ({
subcategory: state['hrm-form'].hrmForm.subcategory,
});
const mapDispatchToProps = (dispatch) => ({
updateForm: bindActionCreators(Actions.updateForm, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(HrmForm);
HrmForm.jsx (snippet)
render() {
if (!this.props.task) {
return null;
}
return (
<HrmFormComponentStyles>
<form onSubmit={this.handleSubmit}>
<label>
Subcategory:
<input type="text" value={this.props.subcategory}
onChange={this.props.updateForm} />
</label>
<input type="submit" value="Submit" />
</form>
</HrmFormComponentStyles>
);
}

Vue.JS not update data into nested Component

I'm working with 3 VUE nested components (main, parent and child) and I'm getting trouble passing data.
The main component useget a simple API data based on input request: the result is used to get other info in other component.
For example first API return the regione "DE", the first component is populated then try to get the "recipes" from region "DE" but something goes wrong: The debug comments in console are in bad order and the variable used results empty in the second request (step3):
app.js:2878 Step_1: DE
app.js:3114 Step_3: 0
app.js:2890 Step_2: DE
This is the parent (included in main component) code:
parent template:
<template>
<div>
<recipes :region="region"/>
</div>
</template>
parent code:
data: function () {
return {
region: null,
}
},
beforeRouteEnter(to, from, next) {
getData(to.params.e_title, (err, data) => {
console.log("Step_1: "+data.region); // return Step_1: DE
// here I ned to update the region value to "DE"
next(vm => vm.setRegionData(err, data));
});
},
methods: {
setRegionData(err, data) {
if (err) {
this.error = err.toString();
} else {
console.log("Step_2: " + data.region); // return DE
this.region = data.region;
}
}
},
child template:
<template>
<div v-if="recipes" class="content">
<div class="row">
<recipe-comp v-for="(recipe, index) in recipes" :key="index" :title="recipe.title" :vote="recipe.votes">
</recipe-comp>
</div>
</div>
</template>
child code:
props: ['region'],
....
beforeMount () {
console.log("Step_3 "+this.region); // Return null!!
this.fetchData()
},
The issue should be into parent beforeRouteEnter hook I think.
Important debug notes:
1) It looks like the child code works properly because if I replace the default value in parent data to 'IT' instead of null the child component returns the correct recipes from second API request. This confirms the default data is updated too late and not when it got results from first API request.
data: function () {
return {
region: 'IT',
}
},
2) If I use {{region}} in child template it shows the correct (and updated) data: 'DE'!
I need fresh eyes to fix it. Can you help me?
Instead of using the beforeMount hook inside of the child component, you should be able to accomplish this using the watch property. I believe this is happening because the beforeMount hook is fired before the parent is able to set that property.
More on the Vue lifecycle can be found here
More on the beforeMount lifecycle hook can be found here
In short, you can try changing this:
props: ['region'],
....
beforeMount () {
console.log("Step_3 "+this.region); // Return null!!
this.fetchData()
},
To something like this:
props: ['region'],
....
watch: {
region() {
console.log("Step_3 "+this.region); // Return null!!
this.fetchData()
}
},
Cheers!!

What are the rules around the re-rendering of the Apollo Query component?

I have a GraphQL field with the following definition:
query GetData($date: DateTime, $id: Int) {
getData(date: $date, id: $id) {
...Data
}
}
I have been consuming this data in React using the Apollo Client Query component, like so:
ids.map((id) => (
<Query
key={id}
query={Queries.getData}
variables={{
date: date,
id: id,
}}
fetchPolicy="network-only"
>
{({
loading,
error,
data,
}: QueryResult<{ data: any}>) => {
return (
);
}}
</Query>
In a separate component, I have need to reuse this data (for all ids) in the Apollo cache. For this, I wrote a local resolver
resolvers: {
Query: {
getAllData: (parent: any, args: any, cache: any) => {
let count = 0;
args.ids.forEach((id: number) => {
try {
const cacheId = `TypeName:${id}`;
const locationSchedule = client.readFragment({
id: cacheId,
fragment: Fragments.Fragment,
fragmentName: Fragments.Fragment.definitions[0].name.value,
});
// count stuff and store in count variable
} catch (e) {
console.log(e);
}
});
return { count, __typename: 'Test' };
},
},
This is invoked from my other component like so:
<Query
query={Queries.getAllData}
variables={{
date: date,
ids: ids,
}}
//pollInterval={500}
>
{({
loading,
error,
data,
}: QueryResult<{ getAllData: { count: number } }>) => {
const count=
data && data.getAllData && data.getAllData.count;
return (
<li className="actions__group">
<div className="actions__item">
<Button
className={'button button--fill-green'}
onClick={this.onAction}
children={
count? (
<span className="button__badge">
{count}
</span>
) : (
undefined
)
}
disabled={count=== 0}
/>
</div>
</li>
);
}}
</Query>
The problem that I have is that the second Query component (the one with the getAllData query) does not re-render when the cache data is mutated (the first component updates fine). Everything seems to be wired up correctly (when I turn on polling the second component re-renders correctly).
What are the rules around when a Query component re-renders? I can't see why the first component re-renders when the second one does not.

React axios data and multi component search

Hi I am using axios to fetch JSON data in React, the issue is that I am not able to search within the fetched data.
I tried fetching the data in the parent component but the request is asynchronous so it loads child components first and then fetches data.
Below is my code :
axios.get("/url.json")
.then(function(result) {
teams= result.data.teams
});
ReactDOM.render(
<div>
<App teams={teams}/>
</div>
,document.getElementById('app')
)
If I fetch data using axios inside the child component how do I save the data for search? i.e I need to search in the unfiltered data.
Call ReactDOM.render after request succeeding : I mean inside the callback of axios NOT out side.
axios.get("/url.json")
.then(function(result) {
const teams= result.data.teams;
ReactDOM.render(
<div>
<App teams={teams}/>
</div>
,document.getElementById('app')
)
});
..... OR.....
As BEST PRACTICES, you can add another layer (super-parent) which handles this call inside its componentDidMount :
class Root extends React.Component {
constructor() {
super(...arguments);
this.state= {teams : []};
}
componentDidMount() {
axios.get("/url.json")
.then((result) => {
this.setState({teams: result.data.teams})
});
}
render() {
return (
<div>
<App teams={this.state.teams}/>
</div>
)
}
}
ReactDOM.render(
<Root />
,document.getElementById('app')
)

How to set initialValues based on async source such as an ajax call with redux-form

On the official pages and in the GitHub issues for redux-form there are more than one example of how to work with initialValues however I cannot find a single one that focuses on explaining how initialValues can be set in response to an asynchronous source.
The main case that I have in mind is something like a simple CRUD application where a user is going to edit some entity that already exists. When the view is first opened and the redux-form component is mounted but before the component is rendered the initialValues must be set. Lets say that in this example that the data is loaded on demand when the component is first mounted and rendered for the first time. The examples show setting initialValues based on hard coded values or the redux store state but none that I can find focus on how to set the initialValues based on something async like a call to XHR or fetch.
I'm sure I'm just missing something fundamental so please point me in the right direction.
References:
Initializing Form State
Handling form defaults
What is the correct way to populate a dynamic form with initial data?
EDIT: Updated Solution from ReduxForm docs
This is now documented in the latest version of ReduxForm, and is much simpler than my previous answer.
The key is to connect your form component after decorating it with ReduxForm. Then you will be able to access the initialValues prop just like any other prop on your component.
// Decorate with reduxForm(). It will read the initialValues prop provided by connect()
InitializeFromStateForm = reduxForm({
form: 'initializeFromState'
})(InitializeFromStateForm)
// now set initialValues using data from your store state
InitializeFromStateForm = connect(
state => ({
initialValues: state.account.data
})
)(InitializeFromStateForm)
I accomplished this by using the redux-form reducer plugin method.
The following demos fetching async data and pre-populating a user form with response.
const RECEIVE_USER = 'RECEIVE_USER';
// once you've received data from api dispatch action
const receiveUser = (user) => {
return {
type: RECEIVE_USER,
payload: { user }
}
}
// here is your async request to retrieve user data
const fetchUser = (id) => dispatch => {
return fetch('http://getuser.api')
.then(response => response.json())
.then(json => receiveUser(json));
}
Then in your root reducer where you include your redux-form reducer you would include your reducer plugin that overrides the forms values with the returned fetched data.
const formPluginReducer = {
form: formReducer.plugin({
// this would be the name of the form you're trying to populate
user: (state, action) => {
switch (action.type) {
case RECEIVE_USER:
return {
...state,
values: {
...state.values,
...action.payload.user
}
}
default:
return state;
}
}
})
};
const rootReducer = combineReducers({
...formPluginReducer,
...yourOtherReducers
});
Finally you include you combine your new formReducer with the other reducers in your app.
Note The following assumes that the fetched user object's keys match the names of the fields in the user form. If this is not the case you will need to perform an additional step on the data to map fields.
By default, you may only initialize a form component once via initialValues. There are two methods to reinitialize the form component with new "pristine" values:
Pass a enableReinitialize prop or reduxForm() config parameter set to true to allow the form the reinitialize with new "pristine" values every time the initialValues prop changes. To keep dirty form values when it reinitializes, you can set keepDirtyOnReinitialize to true. By default, reinitializing the form replaces all dirty values with "pristine" values.
Dispatch the INITIALIZE action (using the action creator provided by redux-form).
Referenced from : http://redux-form.com/6.1.1/examples/initializeFromState/
Could you fire the dispatch on componentWillMount(), and set the state to loading.
While it is loading, render a spinner for example and only when the request returns with the values, update the state, and then re-render the form with the values??
Here is minimal working example on how to set initialValues based on async source.
It uses initialize action creator.
All values from initialValues shouldn't be undefined, or you will get an infinite loop.
// import { Field, reduxForm, change, initialize } from 'redux-form';
async someAsyncMethod() {
// fetch data from server
await this.props.getProducts(),
// this allows to get current values of props after promises and benefits code readability
const { products } = this.props;
const initialValues = { productsField: products };
// set values as pristine to be able to detect changes
this.props.dispatch(initialize(
'myForm',
initialValues,
));
}
While this method may not be the best solution, it works well enough for my needs:
AJAX request to API on entry
Initializes form with data when request has been fulfilled or displays a server error
Resetting form will still reset to initial seed data
Allows the form to be reused for other purposes (for example, a simple if statement could bypass setting initial values): Add Post and Edit Post or Add Comment and Edit Comment...etc.
Data is removed from Redux form on exit (no reason to store new data in Redux since it's being re-rendered by a Blog component)
Form.jsx:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { browserHistory, Link } from 'react-router';
import { editPost, fetchPost } from '../../actions/BlogActions.jsx';
import NotFound from '../../components/presentational/notfound/NotFound.jsx';
import RenderAlert from '../../components/presentational/app/RenderAlert.jsx';
import Spinner from '../../components/presentational/loaders/Spinner.jsx';
// form validation checks
const validate = (values) => {
const errors = {}
if (!values.title) {
errors.title = 'Required';
}
if (!values.image) {
errors.image = 'Required';
}
if (!values.description) {
errors.description = 'Required';
} else if (values.description.length > 10000) {
errors.description = 'Error! Must be 10,000 characters or less!';
}
return errors;
}
// renders input fields
const renderInputField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} className="form-details complete-expand" placeholder={label} type={type}/>
{touched && error && <div className="error-handlers "><i className="fa fa-exclamation-triangle" aria-hidden="true"></i> {error}</div>}
</div>
</div>
)
// renders a text area field
const renderAreaField = ({ textarea, input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<textarea {...input} className="form-details complete-expand" placeholder={label} type={type}/>
{touched && error && <div className="error-handlers"><i className="fa fa-exclamation-triangle" aria-hidden="true"></i> {error}</div>}
</div>
</div>
)
class BlogPostForm extends Component {
constructor() {
super();
this.state = {
isLoaded: false,
requestTimeout: false,
};
}
componentDidMount() {
if (this.props.location.query.postId) {
// sets a 5 second server timeout
this.timeout = setInterval(this.timer.bind(this), 5000);
// AJAX request to API
fetchPost(this.props.location.query.postId).then((res) => {
// if data returned, seed Redux form
if (res.foundPost) this.initializeForm(res.foundPost);
// if data present, set isLoaded to true, otherwise set a server error
this.setState({
isLoaded: (res.foundPost) ? true : false,
serverError: (res.err) ? res.err : ''
});
});
}
}
componentWillUnmount() {
this.clearTimeout();
}
timer() {
this.setState({ requestTimeout: true });
this.clearTimeout();
}
clearTimeout() {
clearInterval(this.timeout);
}
// initialize Redux form from API supplied data
initializeForm(foundPost) {
const initData = {
id: foundPost._id,
title: foundPost.title,
image: foundPost.image,
imgtitle: foundPost.imgtitle,
description: foundPost.description
}
this.props.initialize(initData);
}
// onSubmit => take Redux form props and send back to server
handleFormSubmit(formProps) {
editPost(formProps).then((res) => {
if (res.err) {
this.setState({
serverError: res.err
});
} else {
browserHistory.push(/blog);
}
});
}
renderServerError() {
const { serverError } = this.state;
// if form submission returns a server error, display the error
if (serverError) return <RenderAlert errorMessage={serverError} />
}
render() {
const { handleSubmit, pristine, reset, submitting, fields: { title, image, imgtitle, description } } = this.props;
const { isLoaded, requestTimeout, serverError } = this.state;
// if data hasn't returned from AJAX request, then render a spinner
if (this.props.location.query.postId && !isLoaded) {
// if AJAX request returns an error or request has timed out, show NotFound component
if (serverError || requestTimeout) return <NotFound />
return <Spinner />
}
// if above conditions are met, clear the timeout, otherwise it'll cause the component to re-render on timer's setState function
this.clearTimeout();
return (
<div className="col-sm-12">
<div className="form-container">
<h1>Edit Form</h1>
<hr />
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<Field name="title" type="text" component={renderInputField} label="Post Title" />
<Field name="image" type="text" component={renderInputField} label="Image URL" />
<Field name="imgtitle" component={renderInputField} label="Image Description" />
<Field name="description" component={renderAreaField} label="Description" />
<div>
<button type="submit" className="btn btn-primary partial-expand rounded" disabled={submitting}>Submit</button>
<button type="button" className="btn btn-danger partial-expand rounded f-r" disabled={ pristine || submitting } onClick={ reset }>Clear Values</button>
</div>
</form>
{ this.renderServerError() }
</div>
</div>
)
}
}
BlogPostForm = reduxForm({
form: 'BlogPostForm',
validate,
fields: ['name', 'image', 'imgtitle', 'description']
})(BlogPostForm);
export default BlogPostForm = connect(BlogPostForm);
BlogActions.jsx:
import * as app from 'axios';
const ROOT_URL = 'http://localhost:3001';
// submits Redux form data to server
export const editPost = ({ id, title, image, imgtitle, description, navTitle }) => {
return app.put(`${ROOT_URL}/post/edit/${id}?userId=${config.user}`, { id, title, image, imgtitle, description, navTitle }, config)
.then(response => {
return { success: response.data.message }
})
.catch(({ response }) => {
if(response.data.deniedAccess) {
return { err: response.data.deniedAccess }
} else {
return { err: response.data.err }
}
});
}
// fetches a single post from the server for front-end editing
export const fetchPost = (id) => {
return app.get(`${ROOT_URL}/posts/${id}`)
.then(response => {
return { foundPost: response.data.post}
})
.catch(({ response }) => {
return { err: response.data.err };
});
}
RenderAlert.jsx:
import React, { Component } from 'react';
const RenderAlert = (props) => {
const displayMessage = () => {
const { errorMessage } = props;
if (errorMessage) {
return (
<div className="callout-alert">
<p>
<i className="fa fa-exclamation-triangle" aria-hidden="true"/>
<strong>Error! </strong> { errorMessage }
</p>
</div>
);
}
}
return (
<div>
{ displayMessage() }
</div>
);
}
export default RenderAlert;
Reducers.jsx
import { routerReducer as routing } from 'react-router-redux';
import { reducer as formReducer } from 'redux-form';
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
form: formReducer,
routing
});
export default rootReducer;
use this :
UpdateUserForm = reduxForm({
enableReinitialize: true,
destroyOnUnmount: false,
form: 'update_user_form' // a unique identifier for this form
})(UpdateUserForm);
UpdateUserForm = connect(
(state) => ({
initialValues: state.userManagment.userSingle
})
)(UpdateUserForm);
export default UpdateUserForm;

Resources