apollo-link-state cache.writedata results in Missing field warning - apollo

When I call a mutation on my client I get the following warning:
writeToStore.js:111 Missing field updateLocale in {}
This is my stateLink:
const stateLink = withClientState({
cache,
resolvers: {
Mutation: {
updateLocale: (root, { locale }, context) => {
context.cache.writeData({
data: {
language: {
__typename: 'Language',
locale,
},
},
});
},
},
},
defaults: {
language: {
__typename: 'Language',
locale: 'nl',
},
},
});
And this is my component:
export default graphql(gql`
mutation updateLocale($locale: String) {
updateLocale(locale: $locale) #client
}
`, {
props: ({ mutate }) => ({
updateLocale: locale => mutate({
variables: { locale },
}),
}),
})(LanguagePicker);
What am I missing?

I was getting the same warning and solved it by returning the data from the mutation method.
updateLocale: (root, { locale }, context) => {
const data = {
language: {
__typename: 'Language',
locale,
}
};
context.cache.writeData({ data });
return data;
};

At the moment, apollo-link-state requires you to return any result. It can be null too. This might be changed in the future.

Related

Unit test a nestJS interceptor

My interceptor intercepts a GET request and adds a header to the response based on some conditions.
My Controller
#UseInterceptors(ServiceHeaderInterceptor)
#Get('users')
public async users(
#Query('id') Id: number,
#Query('name') Name: string,
){
const setFlags: MetaFlags = {setCacheHeader: false, setServiceHeader: false};
const data = await this.service.getUsers(id, name, setFlags);
return data;
}
My interceptor looks like this
#Injectable()
export class HeaderInterceptor implements NestInterceptor {
public intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<any> {
return next.handle().pipe(
map((data: { data: DataType, header: 'cache' | 'database' }) => {
const req = context.switchToHttp().getResponse();
if (data.header === 'database') {
res.setHeader('x-api-key', 'pretty secure');
} else {
res.setHeader(xyz, value);
}
return data.data;
}),
);
}
}
This is my test class
const users = [
{
'id': 1,
'name': 'Adam',
},
{
'id': 2,
'name': 'Evan',
},
]
const executionContext: any = {
switchToHttp: jest.fn().mockReturnThis(),
getResponse: jest.fn().mockReturnThis(),
setHeader: jest.fn().mockReturnThis(),
};
const next = {
handle: () => of(users),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: UserService,
useValue: mock<UserService>(),
},
ServiceHeaderInterceptor,
],
}).compile();
interceptor = module.get(ServiceHeaderInterceptor);
});
it('get users',async () => {
interceptor.intercept(executionContext, next).subscribe({
next: (value) => {
expect(value).toEqual(users);
},
error: (error) => {
throw error;
},
});
});
});
Is there a way to check what my header values are at this point?
I am able to access only the response body and not the headers.
I need to verify if the header I set in the interceptor is available and has the correct value

chart js not dispalying data array that comes from an axios request

I have an API end point that returns an array of 24 values that I want to use in my chartjs within a vue component.
when the page loads I get no errors but the bars on the charts just don't show and I don't know why.
EDIT: I noticed that the async function returns a promise instead of the actual data:
async filterData() {
await this.$axios.get('/api/data_app/job_count_by_hour/')
.then(response => {
return this.chart_data = response.data;
})
}
here is the data return code, I have a function that populates the chart_data array :
data(){
return {
form:{
day: 'select day',
workspace:'',
machine_family: [],
duration: []
},
res: [],
total:[],
chart_data: [],
url: '/api/jobs/job_count_by_hour/',
days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "sunday"],
barChart2: {
labels: ["6h", "7h", "8h", "9h","10h","11h", "12h", "13h", "14h", "15h", "16h", "17h", "18h", "19h", "20h", "21h","22h", "23h", "00h"],
datasets: [{
label: ["popularity"],
backgroundColor:"#f93232" ,
data: this.chart_data
},],
},
}
},
methods: {
async filterData() {
let _url = `${this.url}`
await this.$axios.get(_url)
.then(response => {
this.chart_data = response.data;
})
return this.chart_data
},
},
mounted() {
this.filterData()
}
}
this is the chart component:
<script>
import { Line } from 'vue-chartjs'
export default {
extends: Line,
props: {
chartdata: {
type: Object,
default: null
},
options: {
type: Object,
default: null
}
},
mounted () {
this.renderChart(this.chartdata, this.options)
}
}
in the parent component It looks like this:
en <BarChart :labels="barChart2.labels"
:datasets="barChart2.datasets"
:height="100"
>
</BarChart>ter code here
Turns out that when you try to update nested data, the component doesn't re-render.
This is how I solved it, I put the entire object in an update function and call that function when i get my data from the back end, I hope this helps!:
methods: {
onInput(value) {
this.filterData()
},
updateChart(data) {
this.datasets = [{
label: ["popularity"],
backgroundColor:"#f93232",
data: data
}]
},
async loadData() {
await this.$axios.get(this.url)
.then(response => {
this.updateChart(response.data)
})
},
},
mounted() {
this.loadData()
},

Why is my Apollo Client optimistic reply failing?

I'm recording this to document the answer to a problem that took me several hours to solve. Scenario:
I'm using two mutation queries on a single component in React Apollo-Client. This is a component wrapped into a larger component to form a page. Something like this (this is not the actual code, but it should give the idea):
import { compose } from 'react-apollo';
// submitNewUser contains
// postedBy
// createdAt
// content
// submitRepository contains
// otherProp
const thisProps1 = {
name: 'mutation1',
props: ({ ownProps, mutation1 }) => ({
submit: ({ repoFullName, commentContent }) => mutation1({
variables: { repoFullName, commentContent },
optimisticResponse: {
__typename: 'Mutation',
submitNewUser: {
__typename: 'Comment',
postedBy: ownProps.currentUser,
content: commentContent,
},
},
}),
}),
};
const thisProps2 = {
name: 'mutation2',
props: ({ ownProps, mutation2 }) => ({
submit: ({ repoFullName, commentContent }) => mutation2({
variables: { repoFullName, commentContent },
optimisticResponse: {
__typename: 'Mutation',
submitRepository: {
__typename: 'Comment',
otherProp: 'foobar',
},
},
}),
}),
};
const ComponentWithMutations = compose(
graphql(submitNewUser, thisProps1),
graphql(submitRepository, thisProps2)
)(Component);
Whenever the optimistic response fires, only the second result is fed back to into the query-response in the outer component. In other words, the first query gives an 'undefined' response (but no error), while the second returns an object as expect.
Why??
The property "createdAt" is not included in the optimistic reply.
__typename: 'Comment',
postedBy: ownProps.currentUser,
content: commentContent,
Should be:
__typename: 'Comment',
postedBy: ownProps.currentUser,
createdAt: Date(),
content: commentContent,
A missing field in an optimistic reply will silently fail to return anything to any queries that call that data.

Apollo: Update React Props on Subscription Update?

Looking at the Apollo docs example code for subscriptions, I am not yet seeing how to update the React props with the subscription results.
From http://dev.apollodata.com/react/subscriptions.html:
Here is a regular query:
import { CommentsPage } from './comments-page.js';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
const COMMENT_QUERY = gql`
query Comment($repoName: String!) {
entry(repoFullName: $repoName) {
comments {
id
content
}
}
}
`;
const withData = graphql(COMMENT_QUERY, {
name: 'comments',
options: ({ params }) => ({
variables: {
repoName: `${params.org}/${params.repoName}`
},
})
});
export const CommentsPageWithData = withData(CommentsPage);
Now, let’s add the subscription.
Note that this sample code appears to leave out this part of the props code for usual queries - from http://dev.apollodata.com/react/queries.html:
props: ({ ownProps, data: { loading, currentUser, refetch } }) => ({
userLoading: loading,
user: currentUser,
refetchUser: refetch,
}),
...which AFAIK is the correct way to update the data props on my React component and trigger a page refresh.
Here is the complete subscription code sample from http://dev.apollodata.com/react/subscriptions.html:
const withData = graphql(COMMENT_QUERY, {
name: 'comments',
options: ({ params }) => ({
variables: {
repoName: `${params.org}/${params.repoName}`
},
}),
props: props => {
return {
subscribeToNewComments: params => {
return props.comments.subscribeToMore({
document: COMMENTS_SUBSCRIPTION,
variables: {
repoName: params.repoFullName,
},
updateQuery: (prev, {subscriptionData}) => {
if (!subscriptionData.data) {
return prev;
}
const newFeedItem = subscriptionData.data.commentAdded;
return Object.assign({}, prev, {
entry: {
comments: [newFeedItem, ...prev.entry.comments]
}
});
}
});
}
};
},
});
How do I get the code shown here, to update the data props on my React component and trigger a page refresh, when the results come in from the non-subscription query COMMENT_QUERY?
Thanks to #neophi on the Apollo Slack for this answer!
const withDataAndSubscription = graphql(GETIMS_QUERY, {
options({toID}) {
console.log(GETIMS_QUERY);
const fromID = Meteor.userId();
return {
fetchPolicy: 'cache-and-network',
variables: {fromID: `${fromID}`, toID: `${toID}`}
};
}
,
props: props => {
return {
loading: props.data.loading,
instant_message: props.data.instant_message,
subscribeToMore: props.data.subscribeToMore,
subscribeToNewIMs: params => {
const fromID = Meteor.userId();
const toID = params.toID;
return props.data.subscribeToMore({
document: IM_SUBSCRIPTION_QUERY,
variables: {fromID: `${fromID}`, toID: `${toID}`},
updateQuery: (previousResult, {subscriptionData}) => {
if (!subscriptionData.data) {
return previousResult;
}
const newMsg = subscriptionData.data.createIM;
return update(previousResult, {
instant_message: {
$push: [newMsg],
},
});
}
});
}
};
},
})
;

Unit testing a React function in component

I need a way to unit test the "edit" function in the code below. It is different form the other questions because my function returns no value.
class QslTable extends React.PureComponent {
this.state = {
data: [{
key: '0',
callSign: {
editable: true,
value: 'F1ABD',
},
QSODate: {
editable: true,
value: '10-05-31',
},
band: {
editable: true,
value: '32',
},
mode: {
editable: true,
value: 'Phone',
},
dxccEntity: {
editable: true,
value: 'France',
},
delete: {
editable: false,
value: 'Delete',
},
}],
};
edit(index) {
const { data } = this.state;
Object.keys(data[index]).forEach((item) => {
if (data[index][item] && typeof data[index][item].editable !== 'undefined') {
data[index][item].editable = true;
}
});
this.setState({ data });
}
}
This doesn't work:
it('should render the component', () => {
const renderedComponent = shallow(<QslTable />);
expect(renderedComponent.find('edit')).toBeDefined();
});
The function doesn't return any value. I have no clue how to test the function. I have looked at the documentation for Jest, but couldn't figure it out. Any help would be appreciated!