Answer the question
In order to leave comments, you need to log in
How to use the same object but with different properties in different components?
Hi, at the time of initialization of the application, I change the real apolloClient
one to a fictitious one, so that instead of requests to the server, give fictitious data. Everything works correctly, but there was a problem, in some components there is the same variable metric
that is assigned different values, (you cannot change the name of the variable in the components), the question is how to use this variable for different components while maintaining the uniqueness of the properties?
An example of data that comes from the server in different requests, for different components:
for one component: {metric: {id: 1, something: "meow"}}
For another: {metric: {id: 2, entities: 50}}
And so, I cannot create two variables metric
or combine data into one variable metric
because the data in the components will not be correct.
The place where I give away my mockups
import {
metric
} from "./mockedData"
export const mocks = {
Query: () => ({
metric // здесь отдаю фиктивные данные в подменный apolloClient
})
}
import ApolloClient from "apollo-client"
import {
makeExecutableSchema,
addMockFunctionsToSchema,
} from "graphql-tools"
import { graphql, print } from "graphql"
import { InMemoryCache } from "apollo-cache-inmemory"
import { ApolloLink, Observable } from "apollo-link"
// simulate loading
function delay(ms) {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, ms)
})
}
function createLink(schema, mocks) {
const delayMs = 1000
return new ApolloLink(operation => new Observable((observer) => {
const { query, operationName, variables } = operation
delay(delayMs)
.then(() => graphql(
schema,
print(query),
{},
{},
variables,
operationName
))
.then(() => {
// inject mocked data here
observer.next({ data: mocks.Query() })
observer.complete()
})
.catch(observer.error.bind(observer))
}))
}
export function createMockedClient({
typeDefs,
mocks,
}) {
const schema = makeExecutableSchema({ typeDefs })
const mockOptions = {
schema,
mocks,
}
addMockFunctionsToSchema(mockOptions)
const cache = new InMemoryCache()
return new ApolloClient({
cache,
link: ApolloLink.from([
createLink(schema, mocks),
]),
connectToDevTools: true,
})
}
Answer the question
In order to leave comments, you need to log in
To complete the picture, it was also necessary to attach a diagram of your component.
If your schema is something like this:
type Metric {
id: Int!
something: String
}
type Metric {
id: Int!
""" Боевая переменная """
something: String
""" Для тестов """
entities: Int
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question