Denormalize fails when trying to use idAttribute to generate id - normalizr

I am using following schema:
import { schema } from 'normalizr';
import { guid } from '../utils/guid';
const track = new schema.Entity('audioTracks');
const audioClip = new schema.Entity('audioclips', {
audioclips: [track],
}, {
idAttribute: (entity, parent) => `${parent.id}:${entity.id}`,
});
const segment = new schema.Entity('segments', {
audioclips: [audioClip],
}
);
const program = new schema.Entity('programs', {
segments: [segment],
});
const json = new schema.Entity('jsons', {
programs: [program],
});
export const portalAttributes = new schema.Entity('portalAttributes');
export const experience = new schema.Entity('experiences', {
json,
portalAttributes,
});
My data uses same id's in the audioclip part, which I don't want to merge. Since they will contain unique data eventually.
The normalize part worked as expected, however when I try to denormalize data back it fails with following error:
TypeError: Cannot read property 'id' of undefined
at EntitySchema.idAttribute (http://localhost:4040/main.bundle.js:3782:59)
at EntitySchema.getId (http://localhost:4040/vendor.bundle.js:70706:19)
at unvisitEntity (http://localhost:4040/vendor.bundle.js:4787:19)
at unvisit (http://localhost:4040/vendor.bundle.js:4821:14)
at http://localhost:4040/vendor.bundle.js:70589:12
at Array.map (native)
at denormalize (http://localhost:4040/vendor.bundle.js:70588:37)
Please help denormalize data back.
All I do at this stage is:
const normalized = normalize(payload, norm.experience);
const denorm = denormalize(normalized.result, norm.experience, normalized.entities)
I can provide the input data as well on demand, it is kinda large.

There is currently a pull request out to fix this precise issue that I also ran into. I would suggest you comment on it that you also would like this solution so that it can be merged! https://github.com/paularmstrong/normalizr/pull/294

Related

React Query queryClient.setQueryData isn't updating the cached data

I have a custom hook that looks something like this:
import { useQuery, useQueryClient } from 'react-query'
import { get } from '#/util/api' // Custom API utility
import produce from 'immer' // Using immer for deep object mutation
export function useData() {
const queryClient = useQueryClient()
const { data, isSuccess } = useQuery(
'myData', () => get('data')
)
function addData(moreData) {
const updatedData = produce(data.results, (draft) => {
draft.push(moreData)
})
setData(updatedData)
}
function setData(newData) {
queryClient.setQueryData('myData', newData)
}
return {
data: data && data.results,
setData,
addData,
}
}
My data in data.results is an array of objects. When I call addData it creates a copy of my current data, mutates it, then calls setData where queryClient.setQueryData is called with a new array of objects passed in as my second argument. But my cached data either doesn't update or becomes undefined in the component hooked up to the useData() hook. Does anyone know what I'm doing wrong?
code looks good from react-query perspective, but I'm not sure if that's how immer works. I think with your code, you will get back the same data instance with just a new data.results object on it. I would do:
const updatedData = produce(data, (draft) => {
draft.results.push(moreData)
})

Why do I not have an Apollo cache-hit between a multi-response query and a single-item query for the same type?

I'm working on a vue3 project using #vue/apollo-composable and #graphql-codegen.
My index page does a search query. Each result from that query has a tile made on the page. I'm expecting the tile queries will be answered by the cache, but instead, they always miss.
At the page level I do this query:
query getTokens($limit: Int!) {
tokens(limit: $limit) {
...tokenInfo
}
}
Inside of the tile component I execute:
query getToken($id: uuid!){
token(id: $id) {
...tokenInfo
}
}
The fragment looks like this:
fragment tokenInfo on token {
id
name
}
Expectation: The cache would handle 100% of the queries inside the tile components. (I'm hoping to avoid the downfalls of serializing this data to vuex).
Reality: I get n+1 backend calls. I've tried a bunch of permutations including getting rid of the fragment. If I send the getToken call with fetchPolicy: 'cache-only' no data is returned.
The apollo client configuration is very basic:
const cache = new InMemoryCache();
const defaultClient = new ApolloClient({
uri: 'http://localhost:8080/v1/graphql',
cache: cache,
connectToDevTools: true,
});
const app = createApp(App)
.use(Store, StateKey)
.use(router)
.provide(DefaultApolloClient, defaultClient);
I'm also attaching a screenshot of my apollo dev tools. It appears that the cache is in fact getting populated with normalized data:
Any help would be greatly appreciated! :)
I've gotten this worked out thanks to #xadm's comment as well as some feedback I received on the Vue discord. Really my confusion is down to me being new to so many of these tools. Deciding to live on the edge and be a vue3 early adopter (which I love in many ways) made it even easier for me to be confused with the variance in documentation qualities right now.
That said, here is what I've got as a solution.
Problem: The actual problem is that, as configured, Apollo has no way to know that getTokens and getToken return the same type (token).
Solution: The minimum configuration I've found that resolves this is as follows:
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
token(_, { args, toReference }) {
return toReference({
__typename: 'token',
id: args?.id,
});
},
},
},
},
});
However, the feels.... kinda gross to me. Ideally, I'd love to see a way to just point apollo at a copy of my schema, or a schema introspection, and have it figure this out for me. If someone is aware of a better way to do that please let me know.
Better(?) Solution: In the short term here what I feel is a slightly more scalable solution:
type CacheRedirects = Record<string, FieldReadFunction>;
function generateCacheRedirects(types: string[]): CacheRedirects {
const redirects: CacheRedirects = {};
for (const type of types) {
redirects[type] = (_, { args, toReference }) => {
return toReference({
__typename: type,
id: args?.id,
});
};
}
return redirects;
}
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
...generateCacheRedirects(['token']),
},
},
},
});
If anyone has any improvements on these, please add a comment/solution! :)

async update(params, data, { files } = {}) does not work

my project was created with Strapi 3.0.0-beta.18.6.
But in the service of the content type "Orders" the (new) "update" method does not work, only the (old) "edit" works.
Can someone give me a tip?
// ---------------- "update" does not work :( ------------------
async update(params, data, { files } = {}) {
const query = strapi.query('order');
const entry = await query.update(params, data);
if (files) {
// automatically uploads the files based on the entry and the model
await this.uploadFiles(entry, files, { model: strapi.models.order });
return this.findOne({ id: entry.id });
}
return entry;
},
by the way, query.update(params, data); cannot be executed, the process is canceled, but there is no error message.
// ---------------- old "edit" works ------------------
async edit (params, values) {
// Extract values related to relational data.
const relations = _.pick(values, Order.associations.map(ast => ast.alias));
const data = _.omit(values, Order.associations.map(ast => ast.alias));
// Create entry with no-relational data.
const entry = Order.forge(params).save(data);
// Create relational data and return the entry.
return Order.updateRelations(Object.assign(params, { values: relations }));
},
Thanks in advance!
Strapi generated controllers are based on the shadow core controller function.
If you want to customize the default function you can refer to this documentation : https://strapi.io/documentation/3.0.0-beta.x/concepts/controllers.html#core-controllers
I just tried it and it works fine.

reselect across multiple comoponents work only with deepEqual check

I've tested in various ways... Still, It isn't working.
I don't seem to doing anything wrong
exactly same code as reselect doc
redux store is all normalized
reducers are all immutable
From parent component, I just pass down a prop with id and from child component, connected with redux and used selector to get that exact item by id(from parent component)
### This is what Parent components render looks like
render() {
return (
<div>
<h4>Parent component</h4>
{this.props.sessionWindow.tabs.map(tabId =>
<ChildComponentHere key={tabId} tabId={tabId} />
)}
</div>
);
}
### This is what Child component looks like
render() {
const { sessionTab } = this.props (this props is from connect() )
<div>
<Tab key={sessionTab.id} tab={sessionTab} />
</div>
))
}
### Selectors for across multiple components
const getTheTab = (state: any, ownProps: IOwnProps) => state.sessionWindows.sessionTab[ownProps.tabId];
const makeTheTabSelector = () =>
createSelector(
[getTheTab],
(tab: object) => tab
)
export const makeMapState = () => {
const theTabSelector = makeTheTabSelector();
const mapStateToProps = (state: any, props: IOwnProps) => {
return {
sessionTab: theTabSelector(state, props)
}
}
return mapStateToProps
}
Weirdly Working solution: just change to deep equality check.(from anywhere)
use selectors with deep equality works as expected.
at shouldComponentUpdate. use _.isEqual also worked.
.
1. const createDeepEqualSelector = createSelectorCreator(
defaultMemoize,
isEqual
)
2. if (!_isEqual(this.props, nextProps) || !_isEqual(this.state, nextState)){return true}
From my understanding, my redux is always immutable so when something changed It makes new reference(object or array) that's why react re-renders. But when there is 100 items and only 1 item changed, only component with that changed props get to re-render.
To make this happen, I pass down only id(just string. shallow equality(===) works right?)using this id, get exact item.(most of the components get same valued input but few component get different valued input) Use reselect to memoize the value. when something updated and each component get new referenced input compare with memoized value and re-render when something trully changed.
This is mostly what I can think of right now... If I have to use _isEqual anyway, why would use reselect?? I'm pretty sure I'm missing something here. can anyone help?
For more clarification.(hopefully..)
First,My redux data structure is like this
sessionWindow: {
byId: { // window datas byId
"windowId_111": {
id: "windowId_111",
incognito: false,
tabs: [1,7,3,8,45,468,35,124] // this is for the order of sessionTab datas that this window Item has
},
"windowId_222": {
id: "windowId_222",
incognito: true,
tabs: [2, 8, 333, 111]
},{
... keep same data structure as above
}
},
allIds: ["windowId_222", "windowId_111"] // this is for the order of sessionWindow datas
}
sessionTab: { // I put all tab datas here. each sessionTab doesn't know which sessionWindow they are belong to
"1": {
id: 1
title: "google",
url: "www.google.com",
active: false,
...more properties
},
"7": {
id: 7
title: "github",
url: "www.github.com",
active: true
},{
...keep same data structure as above
}
}
Problems.
1. when a small portion of data changed, It re-renders all other components.
Let's say sessionTab with id 7's url and title changed. At my sessionTab Reducer with 'SessionTabUpdated" action dispatched. This is the reducer logic
const updateSessionTab = (state, action) => {
return {
...state,
[action.tabId]: {
...state[action.tabId],
title: action.payload.title,
url: action.payload.url
}
}
}
Nothing is broken. just using basic reselect doesn't prevent from other components to be re-rendered. I have to use deep equality version to stop re-render the component with no data changed
After few days I've struggled, I started to think that the problem is maybe from my redux data structure? because even if I change one item from sessionTab, It will always make new reference like {...state, [changedTab'id]: {....}} In the end, I don't know...
Three aspects of your selector definition and usage look a little odd:
getTheTab is digging down through multiple levels at once
makeTheTabSelector has an "output selector" that just returns the value it was given, which means it's the same as getTheTab
In mapState, you're passing the entire props object to theTabSelector(state, props).
I'd suggest trying this, and see what happens:
const selectSessionWindows = state => state.sessionWindows;
const selectSessionTabs = createSelector(
[selectSessionWindows],
sessionWindows => sessionWindows.sessionTab
);
const makeTheTabSelector = () => {
const selectTabById = createSelector(
[selectSessionTabs, (state, tabId) => tabId],
(sessionTabs, tabId) => sessionTabs[tabId]
);
return selectTabById;
}
export const makeMapState() => {
const theTabSelector = makeTheTabSelector();
const mapStateToProps = (state: any, props: IOwnProps) => {
return {
sessionTab: theTabSelector(state, props.tabId)
}
}
return mapStateToProps
}
No guarantees that will fix things, but it's worth a shot.
You might also want to try using some devtool utilities that will tell you why a component is re-rendering. I have links to several such tools in the Devtools#Component Update Monitoring section of my Redux addons catalog.
Hopefully that will let you figure things out. Either way, leave a comment and let me know.

How do items in an object from one function transfer into another function?

I am learning react redux, I am using firebase for storing data.
I installed thunk middleware. Everything works, I just don't understand why.
As I understand it, the const expense is an object which is in another function's scope. How can addExpense gets access to it?
export const addExpense = (expense) => ({
type: 'ADD_EXPENSE',
expense
});
export const startAddExpense = (expenseData = {}) => {
return (dispatch) => {
const {
description = '',
note = '',
amount = 0,
createdAt = 0
} = expenseData;
const expense = { description, note, amount, createdAt };
database.ref('expenses').push(expense).then((ref) => {
dispatch(addExpense({
id: ref.key,
...expense
}));
});
};
};
startAddExpense is passing the const expense object to your addExpense function, along with an id field. It just so happens that the argument to addExpense is also called expense, which is where you might be getting confused.
Hope that clears it up.

Resources