React state update issue - javascript

I try to add new arrays and values in a state.
I'm using react-beautiful-dnd to display this state datas.
my initial state :
const initialData = {
users: {
'user-1': { id: 'user-1', name: 'John'},
'user-2': { id: 'user-2', name: 'Patrick'},
'user-3': { id: 'user-3', name: 'Malorie'},
'user-4': { id: 'user-4', name: 'Eric'},
'user-5': { id: 'user-5', name: 'Bob'},
'user-6': { id: 'user-6', name: 'Blob'}
},
areas: {
'area-0': {
id: 'area-0',
title: 'Main Area',
userIds: ['user-1', 'user-2','user-3', 'user-4','user-5', 'user-6']
},
'area-1': {
id: 'area-1',
title: 'Area 1',
userIds: []
},
'area-2': {
id: 'area-2',
title: 'Area 2',
userIds: []
}
},
areaOrder: ['area-0','area-1', 'area-2'],
}
class MyClass {
constructor() {
super();
this.state = {
data: initialData,
}
}
...
}
I have a dropdown menu to choose the number of areas I want to display in total, when I trigger it, I try to add the new areas in the 'areas' array and in 'areOrder' array.
If I update the number of areas again, I need to reset the state to 'initialData'.
the code in MyClass:
// apply is triggered by the dropdown menu
apply = (numOfAreas) => {
// clear state to initial data
this.setState({
data: initialData
})
for (let i = 3; i <= numOfBOR; i++ ) {
this.addNewArea(i);
}
}
addNewArea = (newRoomId) => {
const areas = { ...this.state.data.areas };
let p = "area-";
let key = newAreaId;
const newAreaKey = p.concat(key);
const areaTitle = "Area ".concat(newAreaId);
let obj = [];
obj[newAreaKey] = { id: newAreaKey, title: areaTitle, userIds: [] };
const currentAreas = { ...areas };
const newAreaObj = Object.assign(currentAreas, obj);
const newState = {
...this.state.data,
areas: newAreaObj,
areaOrder: [...this.state.data.areaOrder, newAreaKey]
};
this.setState({data: newState});
};
When I use the code above, only the last area is displayed(i.e. when I chose 8 areas, the area 8 is display after area 2)
I'm aware that setState is asynch, so I'd like to know which method will allow me to do what I want.

In your case setState doesn't use previous state, so each setState change areas to its initial value plus one new element. You can use this.setState(prevState => newState) to get previous state.

Related

Javascript - Optimize algorithm (complex data strcuture)

Introduction
I am implementing a method which inserts posts to the respective users posts lists in my map, sorted by date (recent posts first).
This is how I am structuring my data:
state = {
userId: {
posts: [
{ // object returned from my feeds algorithm in the server side
id,
userData: {
id,
},
date,
},
... more posts ...
],
},
... more users ...
}
In my algorithm, I just need to insert all the posts that are inside a given list
[
{ id: "post1", { userData: { id: "alex" }, date },
{ id: "post2", { userData: { id: "sara" }, date }
]
in the posts list of each respective user.
Problem
I also need to avoid inserting posts that already exists in my state, and I can't find a simple way to do it optimally.
Current code
This is my current implementation. I feel that this can be done easier and faster. Any help?
/*
Algorithm
*/
function addContents(state, contents, contentType, cached) {
const newState = state;
contents.forEach((content) => {
const { userData: { id: userId } } = content;
const prevUserState = state.get(userId);
const prevContents = prevUserState?.[contentType] ?? [];
const newContents = prevContents;
// TODO - Avoid inserting if already exists in prevContents! (check by **id**)
let inserted = false;
for (const [index, prevContent] of prevContents.entries()) {
// Replace
if (content.id === prevContent.id) {
newContents[index] = content;
inserted = true;
break;
}
// Insert in the correct order
if(content.date >= prevContent.date) {
newContents.splice(index, 0, content);
inserted = true;
break;
}
}
if (!inserted) {
newContents.push(content);
}
newState.set([
userId,
{
...prevUserState,
[contentType]: newContents
}
]);
});
// if(isEqual(state, newState)) return state; (deep compare to avoid re-renderizations because of state update)
return new Map([...newState]);
}
/*
Test
*/
(() => {
// State
const state = new Map([]);
// User ALEX
const userId1 = "alex";
const userPosts1 = [ // already sorted by date
{
id: "78q78w0w0",
userData: {
id: userId1,
},
date: new Date("10/26/1999 00:00:01")
},
{
id: "92uwdq092",
userData: {
id: userId1,
},
date: new Date("10/26/1999 00:00:00")
}
];
state.set(userId1, { posts: userPosts1 });
// User SARA
const userId2 = "sara";
const userPosts2 = [ // already sorted by date
{
id: "iipzxx115",
userData: {
id: userId2,
},
date: new Date("12/25/2003 03:30:10")
},
{
id: "Wxrr22232",
userData: {
id: userId2,
},
date: new Date("01/01/2000 17:44:41")
}
];
state.set(userId2, { posts: userPosts2 });
const newPosts = [
{
id: "OLDEST FOR ALEX!",
userData: {
id: userId1
},
date: new Date("10/25/1999 23:59:59")
},
{
id: "NEWEST FOR SARA!",
userData: {
id: userId2
},
date: new Date("01/05/2010 22:22:22")
},
{
id: "OLDEST FOR SARA!",
userData: {
id: userId2
},
date: new Date("10/25/1999 23:59:59")
}
]
addContents(state, newPosts, "posts");
console.log(state.get(userId1))
console.log(state.get(userId2))
})();
Note: As this method is implemented in a React's reducer, to manage complex states, I am returning a new Map, after deep comparing the previous and the new state, to produce UI re-renderizations.
UPDATE
I have implemented another version where I do what I need, but maybe, it can be more optimized.
function addContents(state, contents, contentType, cached) {
const newState = state;
const exists = {}; // optimization
for (const content of contents) {
const {
userData: { id: userId },
} = content;
const prevUserState = state.get(userId);
const prevContents = prevUserState?.[contentType] ?? [];
const newContents = prevContents;
if (cached) {
if (!exists[userId]) {
exists[userId] = prevContents.reduce((map, content) => {
map[content.id] = true;
return map;
}, {});
}
// Avoid inserting if necessary
if (exists[userId][content.id]) {
break;
}
}
// Insert the new content in the user's content list
console.log(`Inserting ${content.id}`);
let inserted = false;
for (const [index, prevContent] of prevContents.entries()) {
// Replace
if (content.id === prevContent.id) {
newContents[index] = content;
inserted = true;
break;
}
// Insert in the correct order
if(content.date >= prevContent.date) {
newContents.splice(index, 0, content);
inserted = true;
break;
}
}
if (!inserted) {
newContents.push(content);
}
newState.set([
userId,
{
...prevUserState,
[contentType]: newContents
}
]);
}
// if (isEqual(state, newState)) return state;
return new Map([...newState]);
}
/*
Test
*/
(() => {
// State
let state = new Map([]);
// User ALEX
const userId1 = "alex";
const userPosts1 = [ // already sorted by date
{
id: "78q78w0w0",
userData: {
id: userId1,
},
date: new Date("10/26/1999 00:00:01")
},
{
id: "92uwdq092",
userData: {
id: userId1,
},
date: new Date("10/26/1999 00:00:00")
}
];
state.set(userId1, { posts: userPosts1 });
// User SARA
const userId2 = "sara";
const userPosts2 = [ // already sorted by date
{
id: "iipzxx115",
userData: {
id: userId2,
},
date: new Date("12/25/2003 03:30:10")
},
{
id: "Wxrr22232",
userData: {
id: userId2,
},
date: new Date("01/01/2000 17:44:41")
}
];
state.set(userId2, { posts: userPosts2 });
const newPosts = [
{
id: "OLDEST FOR ALEX!",
userData: {
id: userId1
},
date: new Date("10/25/1999 23:59:59")
},
{
id: "NEWEST FOR SARA!",
userData: {
id: userId2
},
date: new Date("01/05/2010 22:22:22")
},
{
id: "OLDEST FOR SARA!",
userData: {
id: userId2
},
date: new Date("10/25/1999 23:59:59")
}
]
state = addContents(state, newPosts, "posts");
console.log(state.get(userId1))
console.log(state.get(userId2))
/*
Insert again!
*/
state = addContents(state, newPosts, "posts", true);
})();
use an object instead of an array:
This is the same concept of the normalizr library for redux: https://github.com/paularmstrong/normalizr
state = {
[user1Id]: {
posts: {
[post1Id]: {
id,
userData: {
id,
},
date,
},
[post2Id]: {
id,
userData: {
id,
},
date,
},
... more posts ...
},
},
... more users ...
}
This way you can easily access the object you want by its Id and check whether it exists or not just doing: if(state[23].posts[12])
if you need to iterate the users or a user posts use
object.keys(state).map(userId => ...)
or
object.keys(state[23].posts).map(postId => ...)
INSERT/UPDATE:
state[23].posts[newId]: { ...newPost}
I'm not able to follow what you are doing but I think this is what you are after.
You can do it to a oneline very easy.
newdata = [{ id: "post1", { userData: { id: "alex" }, date }]
if(!oldstates.find(d =>
d.id === newdata.id &&
d.userData.id === newdata.userData.id &&
d.date === newdata.date
)) {
oldstates.push(newdata)
}
// oneliner
if(!oldstates.find(d => d.id === newdata.id && d.userData.id === newdata.userData.id && d.date === newdata.date )) oldstates.push(newdata)

Fast access to json tree data structure

I have a reducer which holds tree data structure (more then 100_000 items total). This is what the data looks like
[
{
text: 'A',
expanded: false,
items:
[
{
text: 'AA',
expanded: false
},
{
text: 'AB',
expanded: false,
items:
[
{
text: 'ABA',
expanded: false,
},
{
text: 'ABB',
expanded: false,
}
]
}
]
},
{
text: 'B',
expanded: false,
items:
[
{
text: 'BA',
expanded: false
},
{
text: 'BB',
expanded: false
}
]
}
]
What I need to do is access this items really fast using text as an id (need to toggle expanded each time user clicks on item in a treeview). Should I just copy whole structure in to dictionary or is there a better way?
Maybe the following will help, let me know if you need more help but please create a runnable example (code snippet) that shows the problem:
const items = [
{
text: 'A',
expanded: false,
items: [
{
text: 'AA',
expanded: false,
},
{
text: 'AB',
expanded: false,
items: [
{
text: 'ABA',
expanded: false,
},
{
text: 'ABB',
expanded: false,
},
],
},
],
},
{
text: 'B',
expanded: false,
items: [
{
text: 'BA',
expanded: false,
},
{
text: 'BB',
expanded: false,
},
],
},
];
//in your reducer
const mapItems = new Map();
const createMap = (items) => {
const recur = (path) => (item, index) => {
const currentPath = path.concat(index);
mapItems.set(item.text, currentPath);
//no sub items not found in this path
if (!item.items) {
return;
}
//recursively set map
item.items.forEach(recur(currentPath));
};
//clear the map
mapItems.clear();
//re create the map
items.forEach(recur([]));
};
const recursiveUpdate = (path, items, update) => {
const recur = ([current, ...path]) => (item, index) => {
if (index === current && !path.length) {
//no more subitems to change
return { ...item, ...update };
}
if (index === current) {
//need to change an item in item.items
return {
...item,
items: item.items.map(recur(path)),
};
}
//nothing to do for this item
return item;
};
return items.map(recur(path));
};
const reducer = (state, action) => {
//if you set the data then create the map, this can make
// testing difficult since SET_ITEM works only when
// when you call SET_DATA first. You should not have
// side effects in your reducer (like creating the map)
// I broke this rule in favor of optimization
if (action.type === 'SET_DATA') {
createMap(action.payload); //create the map
return { ...state, items };
}
if (action.type === 'SET_ITEM') {
return {
...state,
items: recursiveUpdate(
mapItems.get(action.payload.text),
state.items,
action.payload
),
};
}
return state;
};
//crate a state
const state = reducer(
{},
{ type: 'SET_DATA', payload: items }
);
const changed1 = reducer(state, {
type: 'SET_ITEM',
payload: { text: 'A', changed: 'A' },
});
const {
items: gone,
...withoutSubItems
} = changed1.items[0];
console.log('1', withoutSubItems);
const changed2 = reducer(state, {
type: 'SET_ITEM',
payload: { text: 'ABB', changed: 'ABB' },
});
console.log('2', changed2.items[0].items[1].items[1]);
const changed3 = reducer(state, {
type: 'SET_ITEM',
payload: { text: 'BA', changed: 'BA' },
});
console.log('3', changed3.items[1].items[0]);
If all you wanted to do is toggle expanded then you should probably do that with local state and forget about storing expanded in redux unless you want to expand something outside of the component that renders the item because expanded is then shared between multiple components.
I think you may mean that the cost of handling a change of expansion is really high (because potentially you close/open a node with 100000 leaves and then 100000 UI items are notified).
However, this worries me as I hope only the expanded UI items exist at all (e.g. you don't have hidden React elements for everything, each sitting there and monitoring a Redux selector in case its part of the tree becomes visible).
So long as elements are non-existent when not expanded, then why is expansion a status known by anything but its immediate parent, and only the parent if it's also on screen?
I suggest that expansion state should be e.g. React state not Redux state at all. If they are on screen then they are expanded, optionally with their children expanded (with this held as state within the parent UI element) and if they are not on screen they don't exist.
Copy all the individual items into a Map<id, Node> to then access it by the ID.
const data = []// your data
// Build Map index
const itemsMap = new Map();
let itemsQueue = [...data];
let cursor = itemsQueue.pop();
while (cursor) {
itemsMap.set(cursor.text, cursor);
if (cursor.items)
for (let item of cursor.items) {
itemsQueue.push(item);
}
cursor = itemsQueue.pop();
}
// Retrieve by text id
console.log(map.get('ABB'));
// {
// text: 'ABB',
// expanded: false,
// }

JavaScript, looping, and functional approach

Data Structure coming back from the server
[
{
id: 1,
type: "Pickup",
items: [
{
id: 1,
description: "Item 1"
}
]
},
{
id: 2,
type: "Drop",
items: [
{
id: 0,
description: "Item 0"
}
]
},
{
id: 3,
type: "Drop",
items: [
{
id: 1,
description: "Item 1"
},
{
id: 2,
description: "Item 2"
}
]
},
{
id: 0,
type: "Pickup",
items: [
{
id: 0,
description: "Item 0"
},
{
id: 2,
description: "Item 2"
}
]
}
];
Each element represents an event.
Each event is only a pickup or drop.
Each event can have one or more items.
Initial State
On initial load, loop over the response coming from the server and add an extra property called isSelected to each event, each item, and set it as false as default. -- Done.
This isSelected property is for UI purpose only and tells user(s) which event(s) and/or item(s) has/have been selected.
// shove the response coming from the server here and add extra property called isSelected and set it to default value (false)
const initialState = {
events: []
}
moveEvent method:
const moveEvent = ({ events }, selectedEventId) => {
// de-dupe selected items
const selectedItemIds = {};
// grab and find the selected event by id
let foundSelectedEvent = events.find(event => event.id === selectedEventId);
// update the found event and all its items' isSelected property to true
foundSelectedEvent = {
...foundSelectedEvent,
isSelected: true,
items: foundSelectedEvent.items.map(item => {
item = { ...item, isSelected: true };
// Keep track of the selected items to update the other events.
selectedItemIds[item.id] = item.id;
return item;
})
};
events = events.map(event => {
// update events array to have the found selected event
if(event.id === foundSelectedEvent.id) {
return foundSelectedEvent;
}
// Loop over the rest of the non selected events
event.items = event.items.map(item => {
// if the same item exists in the selected event's items, then set item's isSelected to true.
const foundItem = selectedItemIds[item.id];
// foundItem is the id of an item, so 0 is valid
if(foundItem >= 0) {
return { ...item, isSelected: true };
}
return item;
});
const itemCount = event.items.length;
const selectedItemCount = event.items.filter(item => item.isSelected).length;
// If all items in the event are set to isSelected true, then mark the event to isSelected true as well.
if(itemCount === selectedItemCount) {
event = { ...event, isSelected: true };
}
return event;
});
return { events }
}
Personally, I don't like the way I've implemented the moveEvent method, and it seems like an imperative approach even though I'm using find, filter, and map.
All this moveEvent method is doing is flipping the isSelected flag.
Is there a better solution?
Is there a way to reduce the amount of looping? Maybe events should be an object and even its items. At least, the lookup would be fast for finding an event, and I don't have to use Array.find initially. However, I still have to either loop over each other non selected events' properties or convert them back and forth using Object.entries and/or Object.values.
Is there more a functional approach? Can recursion resolve this?
Usage and Result
// found the event with id 0
const newState = moveEvent(initialState, 0);
// Expected results
[
{
id: 1,
type: 'Pickup',
isSelected: false,
items: [ { id: 1, isSelected: false, description: 'Item 1' } ]
}
{
id: 2,
type: 'Drop',
// becasue all items' isSelected properties are set to true (even though it is just one), then set this event's isSelected to true
isSelected: true,
// set this to true because event id 0 has the same item (id 1)
items: [ { id: 0, isSelected: true, description: 'Item 0' } ]
}
{
id: 3,
type: 'Drop',
// since all items' isSelected properties are not set to true, then this should remain false.
isSelected: false,
items: [
{ id: 1, isSelected: false, description: 'Item 1' },
// set this to true because event id 0 has the same item (id 2)
{ id: 2, isSelected: true, description: 'Item 2' }
]
}
{
id: 0,
type: 'Pickup',
// set isSelected to true because the selected event id is 0
isSelected: true,
items: [
// since this belongs to the selected event id of 0, then set all items' isSelected to true
{ id: 0, isSelected: true, description: 'Item 0' },
{ id: 2, isSelected: true, description: 'Item 2' }
]
}
]
One of the problems with the current solution is data duplication. You are basically trying to keep the data between the different items in sync. Instead of changing all items with the same id, make sure there are no duplicate items by using an approach closer to what you would find in a rational database.
Let's first normalize the data:
const response = [...]; // data returned by the server
let data = { eventIds: [], events: {}, items: {} };
for (const {id, items, ...event} of response) {
data.eventIds.push(id);
data.events[id] = event;
event.items = [];
for (const {id, ...item} of items) {
event.items.push(id);
data.items[id] = item;
}
}
This should result in:
const data {
eventIds: [1, 2, 3, 0], // original order
events: {
0: { type: "Pickup", items: [0, 2] },
1: { type: "Pickup", items: [1] },
2: { type: "Drop", items: [0] },
3: { type: "Drop", items: [1, 2] },
},
items: {
0: { description: "Item 0" },
1: { description: "Item 1" },
2: { description: "Item 2" },
},
};
The next thing to realize is that the isSelected property of an event is computed based on the isSelected property of its items. Storing this would mean more data duplication. Instead calculate it though a function.
const response = [{id:1,type:"Pickup",items:[{id:1,description:"Item 1"}]},{id:2,type:"Drop",items:[{id:0,description:"Item 0"}]},{id:3,type:"Drop",items:[{id:1,description:"Item 1"},{id:2,description:"Item 2"}]},{id:0,type:"Pickup",items:[{id:0,description:"Item 0"},{id:2,description:"Item 2"}]}];
// normalize incoming data
let data = { eventIds: [], events: {}, items: {} };
for (const {id, items, ...event} of response) {
data.eventIds.push(id);
data.events[id] = event;
event.items = [];
for (const {id, ...item} of items) {
event.items.push(id);
data.items[id] = item;
item.isSelected = false;
}
}
// don't copy isSelected into the event, calculate it with a function
const isEventSelected = ({events, items}, eventId) => {
return events[eventId].items.every(id => items[id].isSelected);
};
// log initial data
console.log(data);
for (const id of data.eventIds) {
console.log(`event ${id} selected?`, isEventSelected(data, id));
}
// moveEvent implementation with the normalized structure
const moveEvent = (data, eventId) => {
let { events, items } = data;
for (const id of events[eventId].items) {
items = {...items, [id]: {...items[id], isSelected: true}};
}
return { ...data, items };
};
data = moveEvent(data, 0);
// log after data applying `moveEvent(data, 0)`
console.log(data);
for (const id of data.eventIds) {
console.log(`event ${id} selected? `, isEventSelected(data, id));
}
// optional: convert structure back (if you still need it)
const convert = (data) => {
const { eventIds, events, items } = data;
return eventIds.map(id => ({
id,
...events[id],
isSelected: isEventSelected(data, id),
items: events[id].items.map(id => ({id, ...items[id]}))
}));
};
console.log(convert(data));
Check browser console, for better ouput readability.
I'm not sure if this answers solves your entire problem, but I hope you got something useful info out of it.

Rendering React/Redux app multiple times on a single page?

I've been working on a React/Redux application for building a quote. A gross simplification of my state would look something like this:
{
account: { name: 'john doe' },
lineItems:[
{ product: {id: 123, ...}, price: 10, units: 5 },
{ product: {id: 124, ...}, price: 10, units: 5 },
],
modifiers: { couponCode: 'asdf', vip: true }
}
and my reducers would be sliced something like this:
const appReducer = combineReducers<GlobalState>({
account: accountReducer,
lineItems: lineItemReducer,
modifiers: modifersReducer,
});
I've just recently gotten a requirements where I would essentially need to be able to render the entire app multiple times on a single page (basically show 1 or more quotes for different accounts on a single page). So a single state would now need to look something like this:
{
quotes: {
"0": {
account: { name: 'john doe' },
lineItems:[
{ product: {id: 123, ...}, price: 10, units: 5 },
{ product: {id: 124, ...}, price: 10, units: 5 },
],
modifiers: { couponCode: 'asdf', vip: true }
},
"1": {
account: { name: 'billy jean' },
lineItems:[
{ product: {id: 123, ...}, price: 10, units: 5 },
],
modifiers: { couponCode: '', vip: false }
},
}
}
But obviously this new state shape doesn't really work with how I've sliced my reducers. Also, seems like I'd have to refactor all my actions so that I know which quote they should be operating on? For example, if I had an action like this:
{
type: 'UPDATE_PRICE'
payload: { productId: 123, newPrice: 15 }
}
Seems like the product 123 on both quotes would be updated.
Maybe there is instead some way I can just render the entire app on the page without having to refactor my entire state? I'm not sure what my best approach would be that wouldn't requirement me to rewrite large portions of the app.
This should give you the idea. It's basically using one reducer inside another one. As simple as using a function within another function body. You can run it on runkit.com as well.
const { createStore, combineReducers } from 'redux';
const UPDATE_ACCOUNT = 'app/updat-account';
const ADD_QUOTE = 'quote/add-quote';
const appActions = {
updateAcount: (q_id, a) => ({ type: UPDATE_ACCOUNT, payload: { q_id, name: a }}),
};
const quoteActions = {
addQuote: q_id => ({ type: ADD_QUOTE, payload: q_id }),
};
const accountReducer = (app = {}, action) => {
const { type, payload } = action;
switch (type) {
case UPDATE_ACCOUNT:
return { ...app, name: payload.name }
default:
return app;
}
};
const appReducer = combineReducers({
account: accountReducer,
lineItems: (app ={}, action) => app, // just a placeholder
modifiers: (app ={}, action) => app, // just a placeholder
});
const quoteReducer = (state = {}, action) => {
const { type, payload } = action;
switch (type) {
case ADD_QUOTE:
return { ...state, [payload]: {} };
case UPDATE_ACCOUNT: {
const app = state[payload.q_id];
return app
? { ...state, [payload.q_id]: appReducer(state[payload.q_id], action) }
: state;
}
default:
return state;
}
}
const store = createStore(quoteReducer);
store.dispatch(quoteActions.addQuote(3));
store.dispatch(quoteActions.addQuote(2));
store.dispatch(appActions.updateAcount(3, 'apple'));
store.dispatch(appActions.updateAcount(4, 'orange')); // non-existent quote
store.getState():
/**
{
"2": {},
"3": {
"account": {
"name": "apple"
},
"lineItems": {},
"modifiers": {}
}
}
*/
Just wanted to add my specific answer here..
Basically I added a new root reducer as norbertpy suggested. However, I also had to add a parameter quoteId to each action to specify which quote the action originated from and should operate on. This was the most time consuming part of the refactor as now each component that dispatches actions must have access to the quote key.
Reducer
const quoteReducer = combineReducers({
account: accountReducer,
lineItems: lineItemReducer,
modifiers: modifersReducer,
});
const rootReducer = (state = {quotes: []}, action) => {
const newQuoteState = quoteReducer(state.quotes[action.quoteId], action);
const newQuotes = {...state.quotes};
newQuotes[action.quoteId] = newQuoteState;
return {...state, ...{quotes: newQuotes}};
};
Action
{
type: 'UPDATE_PRICE'
quoteId: '0',
payload: { productId: 123, newPrice: 15 }
}

aurelia search filtering using a computed is causing issues when rendering to view

I have a search function that retrieves objects
this.searchForObjectByName = () => {
this.server.get('objects/?searchTerm=' + self.searchTerm)
.then(groupObjects=>
{
this.searchResults = groupObjects;
});
}
I then set the result of this to a property called searchResults, which are a groups of objects.
I now want to perform some filtering base on the results. Say I have some groups of objects that look like:
{
id: 1,
name: 'group 1',
objects: [
{
id: 1,
name: 'object name 1',
categories: ['Cat A', 'Cat B']
},
{
id: 2,
name: 'object name 2',
categories: ['Cat A', 'Cat D']
},
{
id: 3,
name: 'object name 3',
categories: ['Cat C', 'Cat D']
}
]
},
{
id: 2,
name: 'group 2',
objects: [
{
id: 4,
name: 'object name 4',
categories: ['Cat A', 'Cat F']
},
{
id: 5,
name: 'object name 5',
categories: ['Cat C', 'Cat D']
}
]
}
I would like to then filter to only show Cat A objects.
I have a computed that filters the search results based on selected categories:
get filteredSearchResults(): any[] {
var filteredGroups = this.searchResults.map(res => {
let filteredGroup = new Group;
filteredGroup = res.id,
filteredGroup = res.name;
filteredGroup = res.objects.filter(o => this.filteredCategories.some(fc => o.categories.some(oc => oc == fc)));
return filteredGroup;
});
filteredGroups = filteredGroups.filter(fg => fg.objects.length > 0);
return filteredGroups;
}
This filters the results fine and I can select different categories and it filters correctly. However it jumps all over the place in the UI, the results are constantly updating due to using a computed to filter the results. I can't use the computedfrom attribute because its based on the filtered categories I've selected (that are an array) and the results returning from the server (also an array). Has anyone else experienced this issue before? Everything I try causes jitter and I'm not sure how I can do this differently.
I could trigger events when selected categories change or when data is returned from the server, I could then recalculate the filtered results. This would work but is hacky and would prefer to be able to do this in a computed
Without computedFrom, your property getter is being polled, which is why your interface is jumping around. I'm not familiar with .some, but I'm guessing order is not guaranteed. While you could simply order your search results to work around this, it would be pretty inefficient to be filtering and sorting an array every 5 seconds.
Using a collection observer your filter code will only be executed when your interface filters actually change. I haven't actually tested this code
import { BindingEngine, Disposable, bindable } from 'aurelia-framework';
export class MyPage
{
#bindable searchTerm: string;
filteredSearchResults: any[];
subscription: Disposable;
constructor(private bindingEngine: BindingEngine)
{
}
attached()
{
this.subscription = this.bindingEngine.collectionObserver(this.filteredCategories).subscribe(this.filtersChanged);
}
detached()
{
this.subscription.dispose();
}
searchTermChanged(newValue: string, oldValue: string)
{
this.find();
}
find()
{
this.server.get('objects/?searchTerm=' + this.searchTerm)
.then(groupObjects=>
{
this.searchResults = groupObjects;
this.update();
});
}
update()
{
// your original filtering logic unchanged
var filteredGroups = this.searchResults.map(res =>
{
let filteredGroup = new Group;
filteredGroup = res.id,
filteredGroup = res.name;
filteredGroup = res.objects.filter(o => this.filteredCategories.some(fc => o.categories.some(oc => oc == fc)));
return filteredGroup;
});
filteredGroups = filteredGroups.filter(fg => fg.objects.length > 0);
// set value instead of using a computed property
this.filteredSearchResults = filteredGroups;
}
filtersChanged(splices)
{
this.update(); // you could remove this method and bind the array observable directly to update()
}
}

Categories

Resources