How to obtain the `initialQueryRef` in Relay? - javascript

In the Relay docs, to fetch a query you have to first preload it using useQueryLoader, and then later pass the result of this into usePreloadedQuery. However, this first step, useQueryLoader takes two arguments: a query itself, which is easy to obtain, and preloadedQueryReference, which the docs do not explain how to obtain. All they say is " e.g. provided by router", but no router actually supports Relay with hooks so this is not helpful information.
As a simple example of this, I have a single component where I want to preload and then use a query:
import {
usePaginationFragment,
usePreloadedQuery,
useQueryLoader
} from "react-relay";
import graphql from 'babel-plugin-relay/macro';
const MY_QUERY = graphql` some stuff here `;
export default function SomeComponent(props) {
const initialRef = ???????;
const [
queryReference,
loadQuery,
disposeQuery,
] = useQueryLoader(AllHits, initialRef);
const qry = usePreloadedQuery(AllHits, queryReference);
}
However without the initialRef, I can't proceed any further. How do I obtain this?

It seems that the query ref is returned from useQueryLoader or loadQuery. The argument to useQueryLoader (initialRef in the original post) is optional, and might be derived from a previous call to loadQuery done by the router, but it in no way required. An example of using useQueryLoader which loads the query as soon as possible is this:
const some_query = graphql` some query here`;
function Parent(props){
// Note, didn't pass in the optional query ref here
const [
queryRef,
loadQuery,
disposeQuery
] = useQueryLoader(some_query);
// Load immediately
useEffect(() => {
loadQuery(
{count: 20},
{fetchPolicy: 'store-or-network'},
);
}, [loadQuery]);
if (!!queryRef) {
return <Child queryRef={queryRef}/>;
} else {
return "loading...";
}
}
export function Child(props) {
const {queryRef} = props;
const loaded = usePreloadedQuery(some_query, queryRef);
const { data } = useFragment(
graphql`some_fragment`,
loaded
);
return JSON.stringify(data);
}

Related

Vue3 Multiple Instances of Composition API Data Store

Simplifying a real-life situation...
Let's say I have a webapp with two columns. The same component used in both columns. The functionality uses data storage and functions created in a separate composition api js file, made available to the component by importing and then provide/inject. Works great.
But is there a way to write the js file with the composition api once, and then create multiple instances when it's imported to the Vue app? That way a separate instance can be sent to each component and they won't share the same data object. I know if you import the same file with multiple names...
import instanceone from "path";
import instancetwo from "path";
...they'll both share the same objects because it's importing the same file as two names, not two instances of the file.
Is there any way to achieve something like this? I'm interested in any setup that would achieve the end goal (not needing two copies of the file to achieve two independent usages). I took a flyer and thought maybe creating a single file that exports objects and functions, then two files that each import the appropriate pieces of that single file, and then let Vue import those two files might work...but nope, not so much.
Obviously there are plenty of other ways to do this, but I want to explore this possibility first. Preferably without making use of Vuex.
Thank you!
the following is one of the way to achieve this
/* composable_module.js */
import { ref, computed } from 'vue';
export const shared_var_1 = ref(0);
export const shared_var_2 = ref(0);
export function composable_variables() {
// will return separate instance of variables for each call
const var1 = ref(0);
const comp_var1 = computed(() => var1.value + shared_var_1.value);
// comp_var1 updates value when either var1 or shared_var_1 value gets updated
return { var1, comp_var1 };
}
usage as following
/* component_1.vue */
import { shared_var_1, shared_var_2, composable_variables } from 'composable_module.js';
/* other things needed for component or any file */
setup() {
const { var1, comp_var1 } = composable_variables();
/*
Do what you want to do with
shared_var_1, shared_var_2, var1, comp_var1
*/
// return whatever you wanted to use in template
return { shared_var_1, shared_var_2, var1, comp_var1 }
}
Here shared_var_1, shared_var_2 will act as vuex store values
and var1, comp_var1 will be separate for each function call
so can be used in multiple components as separate variable sharing common functionality but not value.
Within your 'path' composable you could define two states, then call the relevant state with something like:
const { getItem1, getItem2, setItem1, setItem2 } = (whichInstance) ? instanceOne : instanceTwo
You just need to define your whichInstance condition to determine which instance you want.
Your composable could be something like:
const stateOne = reactive({
item1: true,
item2: 1
})
const stateTwo = reactive({
item1: false,
item2: 2
})
export function instanceOne() {
let stateRef = toRefs(stateOne)
/* Getters */
const getItem1 = () => {
return stateRef.item1
}
const getItem2 = () => {
return stateRef.item2
}
/* Mutations */
const setItem1 = (value) => {
stateRef.item1.value = value
}
const setItem2 = (value) => {
stateRef.item2.value = value
}
return {
state: toRefs(stateOne),
getItem1,
getItem2,
setItem1,
setItem2
}
}
export function instanceTwo() {
let stateRef = toRefs(stateTwo)
/* Getters */
const getItem1 = () => {
return stateRef.item1
}
const getItem2 = () => {
return stateRef.item2
}
/* Mutations */
const setItem1 = (value) => {
stateRef.item1.value = value
}
const setItem2 = (value) => {
stateRef.item2.value = value
}
return {
state: toRefs(stateTwo),
getItem1,
getItem2,
setItem1,
setItem2
}
}
})

How to store nuxtjs dynamically generated routes in vuex store

I'm trying to leverage nuxtjs SSG capabilities by creating a static web site where the pages content and navigation are fetched from an API.
I already found my way around on how to dynamically generate the routes by defining a module where I use the generate:before hook to fetch the pages content and routes. When creating the routes I store the page content as the route payload. The following code does just that and works as intended.
modules/dynamicRoutesGenerator.js
const generator = function () {
//Before hook to generate our custom routes
this.nuxt.hook('generate:before', async (generator, generatorOptions) => {
generator.generateRoutes(await generateDynamicRoutes())
})
}
let generateDynamicRoutes = async function() {
//...
return routes
}
export default generator
Now the problem I'm facing is that I have some navigation components that need the generated routes and I was thinking to store them into the vuex store.
I tried the generate:done hook but I don't know how to get the vuex store context from there. What I ended up using was the nuxtServerInit() action because as stated in the docs:
If nuxt generate is ran, nuxtServerInit will be executed for every dynamic route generated.
This is exactly what I need so I'm trying to use it with the following code:
store/index.js
export const actions = {
nuxtServerInit (context, nuxtContext) {
context.commit("dynamicRoutes/addRoute", nuxtContext)
}
}
store/dynamicRoutes.js
export const state = () => ({
navMenuNivel0: {}
})
export const mutations = {
addRoute (state, { ssrContext }) {
//Ignore static generated routes
if (!ssrContext.payload || !ssrContext.payload.entrada) return
//If we match this condition then it's a nivel0 route
if (!ssrContext.payload.navMenuNivel0) {
console.log(JSON.stringify(state.navMenuNivel0, null, 2));
//Store nivel0 route, we could use url only but only _id is guaranteed to be unique
state.navMenuNivel0[ssrContext.payload._id] = {
url: ssrContext.url,
entrada: ssrContext.payload.entrada,
navMenuNivel1: []
}
console.log(JSON.stringify(state.navMenuNivel0, null, 2));
//Nivel1 route
} else {
//...
}
}
}
export const getters = {
navMenuNivel0: state => state.navMenuNivel0
}
The action is indeed called and I get all the expected values, however it seems like that with each call of nuxtServerInit() the store state gets reset. I printed the values in the console (because I'm not sure even if it's possible to debug this) and this is what they look like:
{}
{
"5fc2f4f15a691a0fe8d6d7e5": {
"url": "/A",
"entrada": "A",
"navMenuNivel1": []
}
}
{}
{
"5fc2f5115a691a0fe8d6d7e6": {
"url": "/B",
"entrada": "B",
"navMenuNivel1": []
}
}
I have searched all that I could on this subject and altough I didn't find an example similar to mine, I put all the pieces I could together and this was what I came up with.
My idea was to make only one request to the API (during build time), store everything in vuex then use that data in the components and pages.
Either there is a way of doing it better or I don't fully grasp the nuxtServerInit() action. I'm stuck and don't know how to solve this problem and can't see another solution.
If you made it this far thanks for your time!
I came up a with solution but I don't find it very elegant.
The idea is to store the the API requests data in a static file. Then create a plugin to have a $staticAPI object that expose the API data and some functions.
I used the build:before hook because it runs before generate:before and builder:extendPlugins which means that by the time the route generation or plugin creation happen, we already have the API data stored.
dynamicRoutesGenerator.js
const generator = function () {
//Add hook before build to create our static API files
this.nuxt.hook('build:before', async (plugins) => {
//Fetch the routes and pages from API
let navMenuRoutes = await APIService.fetchQuery(QueryService.navMenuRoutesQuery())
let pages = await APIService.fetchQuery(QueryService.paginasQuery())
//Cache the queries results into staticAPI file
APIService.saveStaticAPIData("navMenuRoutes", navMenuRoutes)
APIService.saveStaticAPIData("pages", pages)
})
//Before hook to generate our custom routes
this.nuxt.hook('generate:before', async (generator, generatorOptions) => {
console.log('generate:before')
generator.generateRoutes(await generateDynamicRoutes())
})
}
//Here I can't find a way to access via $staticAPI
let generateDynamicRoutes = async function() {
let navMenuRoutes = APIService.getStaticAPIData("navMenuRoutes")
//...
}
The plugin staticAPI.js:
import APIService from '../services/APIService'
let fetchPage = function(fetchUrl) {
return this.pages.find(p => { return p.url === fetchUrl})
}
export default async (context, inject) => {
//Get routes and files from the files
let navMenuRoutes = APIService.getStaticAPIData("navMenuRoutes")
let pages = APIService.getStaticAPIData("pages")
//Put the objects and functions in the $staticAPI property
inject ('staticAPI', { navMenuRoutes, pages, fetchPage })
}
The APIService helper to save/load data to the file:
//...
let fs = require('fs');
let saveStaticAPIData = function (fileName = 'test', fileContent = '{}') {
fs.writeFileSync("./static-api-data/" + fileName + ".json", JSON.stringify(fileContent, null, 2));
}
let getStaticAPIData = function (fileName = '{}') {
let staticData = {};
try {
staticData = require("../static-api-data/" + fileName + ".json");
} catch (ex) {}
return staticData;
}
module.exports = { fetchQuery, apiUrl, saveStaticAPIData, getStaticAPIData }
nuxt.config.js
build: {
//Enable 'fs' module
extend (config, { isDev, isClient }) {
config.node = { fs: 'empty' }
}
},
plugins: [
{ src: '~/plugins/staticAPI.js', mode: 'server' }
],
buildModules: [
'#nuxtjs/style-resources',
'#/modules/staticAPIGenerator',
'#/modules/dynamicRoutesGenerator'
]

Default string value after call the object in JavaScript

I have a js object in which I return my endpoint addresses from api. This is a very nice solution for me, it looks like this:
export const API_BASE_URL = 'http://localhost:3000';
export const USERS = '/Users';
export default {
users: {
checkEmail: (email) => `${API_BASE_URL}${USERS}/${email}/checkEmail`,
notifications: `${API_BASE_URL}${USERS}/notifications`,
messages: `${API_BASE_URL}${USERS}/messages`,
},
};
Now I can call this address in my redux-saga to execute the xhr query:
import { api } from 'utils';
const requestURL = api.users.notifications;
But I'm a bit stuck because now I have a problem - base path is missing here: '/users'.
Now when I call api.users, then I get a object. I would like to have a default value after calling the object like:
import { api } from 'utils';
const requestURL = api.users; // http://localhost:3000/Users
const requestURL2 = api.users.notifications; // http://localhost:3000/Users/notifications
I know that I could add a new string with the name 'base' to the object and add '/Users' there, but I don't like this solution and I think, there is a better solution.
You could do one of the following:
extend the String class
const API_BASE_URL = "http://localhost:3000"
const USERS = "/Users"
class UsersEndpoints extends String {
constructor(base) {
super(base)
}
// this is still a proposal at stage 3 to declare instance variables like this
// if u want a truly es6 way you can move them to the constructor
checkEmail = (email) => `${API_BASE_URL}${USERS}/${email}/checkEmail`
notifications = `${API_BASE_URL}${USERS}/notifications`
messages = `${API_BASE_URL}${USERS}/messages`
}
// you can use userEndpoints itself as a string everywhere a string is expected
const userEndpoints = new UsersEndpoints(API_BASE_URL)
export default {
users: userEndpoints
}
The previous is just actually equivalent to
...
const userEndpoints = new String(API_BASE_URL)
userEndpoints.notifications = `${API_BASE_URL}${USERS}/notifications`
...
Obviously this is not recommended: you should not extend native classes, there are many disadvantages to this approach.
An obvious example is that there could be a conflict between the properties you use and the properties that might be brought by the native class
override the toString method
...
export default {
users: {
checkEmail: (email) => `${API_BASE_URL}${USERS}/${email}/checkEmail`,
notifications: `${API_BASE_URL}${USERS}/notifications`,
messages: `${API_BASE_URL}${USERS}/messages`,
toString: () => API_BASE_URL
},
};
// this is actually not much different than the previous method, since a String is an objet with an overridden toString method.
// That said this method is also not recommended since toString is used in many places in native code, and overriding it just to substitute a string value will make information get lost in such places, error stacks for example
Achieve what u want using the language features intended for such a use case
What you are asking is to make the same variable to have different values in the same time, which is not possible in the language syntax, and it makes sense because it makes it hard to reason about code.
that being said i recommend something of the following nature
// it is also better to use named exports
export const getUsersEndpoint = ({
path = "",
dynamicEndpointPayload = {},
} = {}) => {
switch (path) {
case "notifications":
return `${API_BASE_URL}${USERS}/notifications`
case "messages":
return `${API_BASE_URL}${USERS}/messages`
case "checkEmail":
return `${API_BASE_URL}${USERS}/${dynamicEndpointPayload.email}/checkEmail`
// you still can do checkEmail like this, but the previous is more consistent
// case "checkEmail":
// return (email) => `${API_BASE_URL}${USERS}/${email}/checkEmail`
default:
return `${API_BASE_URL}`
}
}
// you can use it like this
getUsersEndpoint() // returns the base
getUsersEndpoint({path: 'notifications'})
You can extend prototype to achieve this behaviour:
export const API_BASE_URL = 'http://localhost:3000';
export const USERS = '/Users';
const users = `${API_BASE_URL}${USERS}`
const baseUrls = {
checkEmail: (email) => `${users}/${email}/checkEmail`,
notifications: `${users}/notifications`,
messages: `${users}/messages`,
}
Object.setPrototypeOf(users.__proto__, baseUrls);
export default {
users
};
Try having object will all user endpoint and a function that return a value of a end point
const user = {
default: '/users',
notification: '/notification',
profile: '/profile',
getEndPoint(prop) {
if(this[prop] === 'default' ){
return this[prop];
} else {
if(this[prop]) {
return this.default + this[prop];
}
}
}
}
So you can have more end points that come under user and you can simply call
const requestURL = api.user.getEndPoint('default'); // http://localhost:3000/Users
const requestURL2 = api.user.getEndPoint('notifications'); // http://localhost:3000/Users/notification

Using Variables with react-apollo Query

I've attached a query to my React Native component like so:
let getNearbyStoriesQuery = gql`{
getStoriesNearbyByGeoHash(geoHash: "8k"){
id
}
}`;
export default graphql(getNearbyStoriesQuery,
{
props: (props) => {
debugger;
let storiesNearby = props.data.getStoriesNearbyByGeoHash.map((story) => {
return {
id: story.id,
}
});
return {storiesNearby};
},
variables: {
geoHash: mockGeoHash
}
})(Home); // Home is the React Native Component
I'm able to retrieve data from using this technique as long as I hardcode a value in for geoHash in the query; in this case I used "8k". However, when I attempt to modify the query so that I can puss in a variable like so:
let getNearbyStoriesQuery = gql`{
getStoriesNearbyByGeoHash($geoHash: String!){
id
}
}`;
I get an error saying Expected Name, found $. This method of passing variables to queries is repeated across multiple sources. What am I doing wrong here?
Should be:
query GetStoriesNearbyByGeoHash($geoHash: String!) {
getStoriesNearbyByGeoHash(geoHash: $geoHash){
id
}
}
Have a look on how to use variables in graphql: http://graphql.org/learn/queries/#variables

Dispatch Redux action after React Apollo query returns

I'm using React Apollo to query all records in my datastore so I can create choices within a search filter.
The important database model I'm using is Report.
A Report has doorType, doorWidth, glass and manufacturer fields.
Currently when the query responds, I'm passing allReports to multiple dumb components which go through the array and just get the unique items to make a selectable list, like so..
const uniqueItems = []
items.map(i => {
const current = i[itemType]
if (typeof current === 'object') {
if (uniqueItems.filter(o => o.id !== current.id)) {
return uniqueItems.push(current)
}
} else if (!uniqueItems.includes(current)) {
return uniqueItems.push(current)
}
return
})
Obviously this code isn't pretty and it's a bit overkill.
I'd like to dispatch an action when the query returns within my SidebarFilter components. Here is the query...
const withData = graphql(REPORT_FILTER_QUERY, {
options: ({ isPublished }) => ({
variables: { isPublished }
})
})
const mapStateToProps = ({
reportFilter: { isPublished }
// filterOptions: { doorWidths }
}) => ({
isAssessment
// doorWidths
})
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
resetFilter,
saveFilter,
setDoorWidths,
handleDoorWidthSelect
},
dispatch
)
export default compose(connect(mapStateToProps, mapDispatchToProps), withData)(
Filter
)
The Redux action setDoorWidths basically does the code above in the SidebarFilter component but it's kept in the store so I don't need to re-run the query should the user come back to the page.
It's very rare the data will update and the sidebar needs to change.
Hopefully there is a solution using the props argument to the graphql function. I feel like the data could be taken from ownProps and then an action could be dispatched here but the data could error or be loading, and that would break rendering.
Edit:
Query:
query ($isPublished: Boolean!){
allReports(filter:{
isPublished: $isPublished
}) {
id
oldId
dbrw
core
manufacturer {
id
name
}
doorWidth
doorType
glass
testBy
testDate
testId
isAssessment
file {
url
}
}
}
While this answer addresses the specific issue of the question, the more general question -- where to dispatch a Redux action based on the result of a query -- remains unclear. There does not, as yet, seem to be a best practice here.
It seems to me that, since Apollo already caches the query results in your store for you (or a separate store, if you didn't integrate them), it would be redundant to dispatch an action that would also just store the data in your store.
If I understood your question correctly, your intent is to filter the incoming data only once and then send the result down as a prop to the component's stateless children. You were on the right track with using the props property in the graphql HOC's config. Why not just do something like this:
const mapDataToProps = ({ data = {} }) => {
const items = data
const uniqueItems = []
// insert your logic for filtering the data here
return { uniqueItems } // or whatever you want the prop to be called
}
const withData = graphql(REPORT_FILTER_QUERY, {
options: ({ isPublished }) => ({
variables: { isPublished }
}),
props: mapDataToProps,
})
The above may need to be modified depending on what the structure of data actually looks like. data has some handy props on it that can let you check for whether the query is loading (data.loading) or has errors (data.error). The above example already guards against sending an undefined prop down to your children, but you could easily incorporate those properties into your logic if you so desired.

Categories

Resources