Gatsby function returns undefined - javascript

I have a file where I try to determine which data should be used in a Gatsby template. I get an array that contains child pages in return, these child pages may contain other child pages. I want to support up to three levels of child pages.
I have a template where I use my paginator (component to find the correct pages), I look for correct pages to render bypassing the slug via pageContext from gatsby-node.js
Template (minus imports)
const projectsSubPages = ({ data, pageContext }) => {
return (
<Layout>
<Menu parentPage={pageContext.parentSlug} />
{data.allSanityProjects.edges.map((childNode) =>
<>
{childNode.node.childPages.length > 0 &&
<Paginator
pageData={childNode.node.childPages}
parentPage={pageContext.parentSlug}
key={childNode.node._id}
/>
}
</>
)}
</Layout>
);
};
export const query = graphql`
{
allSanityProjects {
edges {
node {
childPages {
_rawBlockContent
title
slug
childPages {
slug
title
childPages {
title
slug
childPages {
slug
title
_key
}
_key
}
_key
}
_key
}
_key
}
}
}
}
`;
export default projectsSubPages;
My paginator component (minus imports)
const subPageLevelFinder = ({ pageData, parentPage }) => {
const SubLevels = () => {
let pageLevel = "test";
if (pageData.slug === parentPage) {
pageLevel = pageData.slug
}
if (pageData.childPages && pageData.childPages.length > 0) {
pageData.childPages.map((secondLevel) => {
if (secondLevel.slug === parentPage) {
pageLevel = secondLevel.slug
return (pageLevel)
} else if (pageData.childPages.childPage && pageData.childPages.childPages.length > 0) {
secondLevel.childPages.map((thirdLevel) => {
if (thirdLevel.slug === parentPage) {
pageLevel = thirdLevel.slug
return (pageLevel)
}
})
} else {
return (
pageLevel = "No page level found"
)
}
})
}
return (
pageLevel
)
}
return (
<>
{console.log(SubLevels())}
{SubLevels()}
</>
)
};
See this gist for the return of the GraphQL query and gatsby-node.js https://gist.github.com/AndreasJacobsen/371faf073a1337b6879e4fd6b860b26f
My goal is to run a component that has a template in my paginator and passing the data this template should use from the SubLevels function, but this function returns the first set let value every time. So all of my if-statements fail, I can't figure out where the issue is, I've tried changing the if parameters several times, but this seems to fit the GraphQL query

It turns out that the error came from my trying to access array elements in a multi dimentional array.
So the array I got back had three elements, all with a slug. I tried to access the slug but in order to get that slug I had to loop through the elements.
See attached solution that works (but is not very efficient), notice that this solution has a map function at the very top level; this solved the issue.
import React from "react";
import SubPageTemplate from "./subPageTemplate";
import { Link } from "gatsby";
import { useStaticQuery, graphql } from "gatsby";
const BlockContent = require("#sanity/block-content-to-react");
const subPageLevelFinder = ({ pageData, parentPage, childSlug }) => {
const subLevels = () => {
let pageLevel = null;
pageData.map((mappedData) => {
if (mappedData.slug === childSlug) {
pageLevel = mappedData;
return pageLevel;
} else {
if (mappedData.childPages && mappedData.childPages.length > 0) {
if (mappedData.slug === childSlug) {
return (pageLevel = mappedData);
} else {
mappedData.childPages.map((secondLevel) => {
if (secondLevel.slug === childSlug) {
pageLevel = secondLevel;
return pageLevel;
} else if (
mappedData.childPages.childPage &&
mappedData.childPages.childPages.length > 0
) {
secondLevel.childPages.map((thirdLevel) => {
if (thirdLevel.slug === childSlug) {
pageLevel = thirdLevel;
return pageLevel;
}
});
}
});
}
} else {
return false;
}
}
});
return pageLevel;
};
return <>{subLevels() && <SubPageTemplate pageLevel={subLevels()} />}</>;
};
export default subPageLevelFinder;

Related

Passing Parameters of a Function React

In my application, I want to conditionally render something, so I made a function getItem which I want to call in my custom Tooltip, const CustomTooltip.
Seen in the code below, I want to pass payload in const CustomTooltip = ({ active, payload, label} to function getState({payload}
I try to do this by {getState(payload, "A")} However, when I do so, I get this error:
Type 'Payload<ValueType, NameType>[]' has no properties in common with type 'TooltipProps<ValueType, NameType>'
Note: I am new to React
const numberStates = 3;
function getState({payload}: TooltipProps<ValueType, NameType>, state: string ){
if(payload){
for(let i = 0; i < numberStates; i++){
if(payload[i].dataKey == state){
return <p>{ payload[i] } : { payload[i].value }</p>
}
}
}
return null;
}
const CustomTooltip = ({ active, payload, label}: TooltipProps<ValueType, NameType>) => {
if(active && payload && payload.length){
return (
<div className = "custom-tooltip">
{getState(payload, "A")}
{getState(payload, "B")}
{getState(payload, "C")}
</div>
);
}
return null;
}
You are passing payload which is of type: Payload<ValueType, NameType>[]
But in getState function you expect TooltipProps<ValueType, NameType>
Change code to this:
function getState(payload: Payload<ValueType, NameType>[], state: string) {
if (payload) {
for (let i = 0; i < numberStates; i++) {
if (payload[i].dataKey === state) {
return (
<p>
{payload[i]} : {payload[i].value}
</p>
);
}
}
}
return null;
}

Handling array of stateful objects in React

I have array of stateful objects (where either size of array or attributes of objects can change). My original plan was having a textfields where user can change course attributes but when i started implementing code. I noticed function changeCourseAttribute and overall code, was becoming more complicated than it should be so my question is there way to handling this, more elegantly ?
Because with my current implementation. For example if i had < CourseComponent /> i would have to call changeCourseAttribute pass all arguments it needs and on top of that it would also call re-render on all components which is unnecesarry.
I would be greatful if anyone could help thanks.
import { React, useState } from "react";
class Semester {
constructor(courses = []) {
this.courses = courses;
}
}
class Course {
constructor(name = "", credits = "", grade = "") {
this.name = name;
this.credits = credits;
this.grade = grade;
}
}
const App = () => {
const [semesters, setSemesters] = useState([new Semester()]);
function addSemester() {
setSemesters([...semesters, new Semester()]);
}
function removeSemester(semesterToBeRemoved) {
if (semesters.length > 1) {
setSemesters(
semesters.filter((semester) => semesterToBeRemoved !== semester)
);
}
}
function addCourse(semesterToBeChanged) {
setSemesters(
semesters.map((semester) =>
semester === semesterToBeChanged
? { ...semester, courses: [...semester.courses, new Course()] }
: semester
)
);
}
function removeCourse(semesterToBeChanged, courseToBeRemoved) {
if (semesterToBeChanged.courses.length > 1) {
setSemesters(
semesters.map((semester) =>
semester === semesterToBeChanged
? {
...semester,
courses: semester.courses.filter(
(course) => course !== courseToBeRemoved
),
}
: semester
)
);
}
}
function changeCourseAttribute(
semesterToBeChanged,
courseToBeChanged,
field,
data
) {
// This is just insanity..
}
return <div>{/* Rest of the code .. */}</div>;
};
export default App;

React infinite scroll component performance

I have written the following infinite scroll component in React:
import React from 'react'
import { uniqueId, isUndefined, hasVerticalScrollbar, hasHorizontalScrollbar, isInt, throttle } from '../../../js/utils';
export default class BlSimpleInfiniteScroll extends React.Component {
constructor(props) {
super(props)
this.handleScroll = this.handleScroll.bind(this)
this.itemsIdsRefsMap = {}
this.isLoading = false
this.node = React.createRef()
}
componentDidMount() {
const {
initialId
} = this.props
let id
if (initialId) {
if (typeof initialId === "function") {
id = initialId()
}
else {
id = initialId
}
this.scrollToId(id)
}
}
componentDidUpdate(prevProps) {
if (
this.isLoading
&&
prevProps.isInfiniteLoading
&&
!this.props.isInfiniteLoading
) {
const axis = this.axis()
const scrollProperty = this.scrollProperty(axis)
const offsetProperty = this.offsetProperty(axis)
this.scrollTo(scrollProperty, this.node.current[offsetProperty])
this.isLoading = false
}
}
itemsRenderer(items) {
const length = items.length
let i = 0
const renderedItems = []
for (const item of items) {
renderedItems[i] = this.itemRenderer(item.id, i, length)
i++
}
return renderedItems
}
itemRenderer(id, i, length) {
const {
itemRenderer,
isInfiniteLoading,
displayInverse
} = this.props
let renderedItem = itemRenderer(id, i)
if (isInfiniteLoading) {
if (!displayInverse && (i == length - 1)) {
renderedItem = this.standardLoadingComponentWrapperRenderer(id, renderedItem)
}
else if (i == 0) {
renderedItem = this.inverseLoadingComponentWrapperRenderer(id, renderedItem)
}
}
const ref = this.itemsIdsRefsMap[id] || (this.itemsIdsRefsMap[id] = React.createRef())
return (
<div className="bl-simple-infinite-scroll-item"
key={id}
ref={ref}>
{renderedItem}
</div>
)
}
loadingComponentRenderer() {
const {
loadingComponent
} = this.props
return (
<div className="bl-simple-infinite-scroll-loading-component"
key={uniqueId()}>
{loadingComponent}
</div>
)
}
loadingComponentWrapperRenderer(id, children) {
return (
<div className="bl-simple-infinite-scroll-loading-component-wrapper"
key={id}>
{children}
</div>
)
}
standardLoadingComponentWrapperRenderer(id, renderedItem) {
return this.loadingComponentWrapperRenderer(id, [
renderedItem,
this.loadingComponentRenderer()
])
}
inverseLoadingComponentWrapperRenderer(id, renderedItem) {
return this.loadingComponentWrapperRenderer(id, [
this.loadingComponentRenderer(),
renderedItem
])
}
axis() {
return this.props.axis === 'x' ? 'x' : 'y'
}
scrollProperty(axis) {
return axis == 'y' ? 'scrollTop' : 'scrollLeft'
}
offsetProperty(axis) {
return axis == 'y' ? 'offsetHeight' : 'offsetWidth'
}
scrollDimProperty(axis) {
return axis == 'y' ? 'scrollHeight' : 'scrollWidth'
}
hasScrollbarFunction(axis) {
return axis == 'y' ? hasVerticalScrollbar : hasHorizontalScrollbar
}
scrollToStart() {
const axis = this.axis()
this.scrollTo(
this.scrollProperty(axis),
!this.props.displayInverse ?
0
:
this.scrollDimProperty(axis)
)
}
scrollToEnd() {
const axis = this.axis()
this.scrollTo(
this.scrollProperty(axis),
!this.props.displayInverse ?
this.scrollDimProperty(axis)
:
0
)
}
scrollTo(scrollProperty, scrollPositionOrPropertyOfScrollable) {
const scrollableContentNode = this.node.current
if (scrollableContentNode) {
scrollableContentNode[scrollProperty] = isInt(scrollPositionOrPropertyOfScrollable) ?
scrollPositionOrPropertyOfScrollable
:
scrollableContentNode[scrollPositionOrPropertyOfScrollable]
}
}
scrollToId(id) {
if (this.itemsIdsRefsMap[id] && this.itemsIdsRefsMap[id].current) {
this.itemsIdsRefsMap[id].current.scrollIntoView()
}
}
handleScroll() {
const {
isInfiniteLoading,
infiniteLoadBeginEdgeOffset,
displayInverse
} = this.props
if (
this.props.onInfiniteLoad
&&
!isInfiniteLoading
&&
this.node.current
&&
!this.isLoading
) {
const axis = this.axis()
const scrollableContentNode = this.node.current
const scrollProperty = this.scrollProperty(axis)
const offsetProperty = this.offsetProperty(axis)
const scrollDimProperty = this.scrollDimProperty(axis)
const currentScroll = scrollableContentNode[scrollProperty]
const currentDim = scrollableContentNode[offsetProperty]
const scrollDim = scrollableContentNode[scrollDimProperty]
const finalInfiniteLoadBeginEdgeOffset = !isUndefined(infiniteLoadBeginEdgeOffset) ?
infiniteLoadBeginEdgeOffset
:
currentDim / 2
let thresoldWasReached = false
let memorizeLastElementBeforeInfiniteLoad = () => { }
if (!displayInverse) {
thresoldWasReached = currentScroll >= (scrollDim - finalInfiniteLoadBeginEdgeOffset)
}
else {
memorizeLastElementBeforeInfiniteLoad = () => {
// TODO
}
thresoldWasReached = currentScroll <= finalInfiniteLoadBeginEdgeOffset
}
if (thresoldWasReached) {
this.isLoading = true
memorizeLastElementBeforeInfiniteLoad()
this.props.onInfiniteLoad()
}
}
}
render() {
const {
items
} = this.props
return (
<div className="bl-simple-infinite-scroll"
ref={this.node}
onScroll={this.handleScroll}
onMouseOver={this.props.onInfiniteScrollMouseOver}
onMouseOut={this.props.onInfiniteScrollMouseOut}
onMouseEnter={this.props.onInfiniteScrollMouseEnter}
onMouseLeave={this.props.onInfiniteScrollMouseLeave}>
{this.itemsRenderer(items)}
</div>
)
}
}
And I use it like this in a chat app I am writing:
...
<BlSimpleInfiniteScroll items={chat.messages}
ref={this.infiniteScrollComponentRef}
initialId={() => lastOfArray(chat.messages).id}
itemRenderer={(id, i) => this.messageRenderer(id, i, chat.messages)}
loadingComponent={<BlLoadingSpinnerContainer />}
isInfiniteLoading={isChatLoading}
displayInverse
infiniteLoadBeginEdgeOffset={void 0}
infiniteLoadingBeginBottomOffset={void 0}
onInfiniteLoad={() => this.props.onLoadPreviousChatMessages(chat.id)}
onInfiniteScrollMouseEnter={this.handleInfiniteScrollMouseEnter}
onInfiniteScrollMouseLeave={this.handleInfiniteScrollMouseLeave} />
...
The problem is that as soon as I scroll until the thresold and onInfiniteLoad is called, before the loading spinner is showed and after the data has been loaded the scroll freezes and the component becomes unresponsive.
How can I resolve this issue?
When I render the spinner container and after the previous loaded messages, shouldn't React just append the new divs retaining the previously added items in order to maintain the component performant?
If not, what key concepts of React I am missing?
Thank you for your attention!
UPDATE: Here are the additional components:
BlOrderChat represents a chat window and renders BlSimpleInfiniteScroll:
import React from 'react'
import BlOrderChatMessage from './BlOrderChatMessage';
import { isEmpty, uniqueId } from '../../../js/utils';
import { chatSelector } from '../selectors';
import BlLoadingSpinnerContainer from '../../core/animation/loading/BlLoadingSpinnerContainer';
import BlSimpleInfiniteScroll from '../../core/scroll/BlSimpleInfiniteScroll';
export default class BlOrderChat extends React.Component {
static BL_ORDER_CHAT_MESSAGE_ID_ATTR_PREFIX = 'blOrderChatMessage'
constructor(props) {
super(props)
this.messageRenderer = this.messageRenderer.bind(this)
this.infiniteScrollComponentRef = React.createRef()
}
scrollToBottom() {
this.infiniteScrollComponentRef.current && this.infiniteScrollComponentRef.current.scrollToStart()
}
messageRenderer(messageId, index, messages) {
const {
currentUser, chat
} = this.props
const message = messages[index]
const length = messages.length
const fromUser = chat.users.items[message.from_user_id]
const itemComponentRender = (children) => (
<div key={messageId}>
{children}
</div>
)
const messageIdAttr = `${BlOrderChat.BL_ORDER_CHAT_MESSAGE_ID_ATTR_PREFIX}${message.id}`
const renderMessageComponent = () => (
<BlOrderChatMessage id={messageIdAttr}
key={uniqueId() + message.id}
message={message.message}
sentUnixTs={message.sent_unix_ts}
currentUser={currentUser}
fromUser={fromUser}
usersInvolvedInChatLength={chat.users.order.length} />
)
let children = []
if (index === 0) {
// First message.
children = [
<div key={uniqueId()} className="bl-padding"></div>,
renderMessageComponent()
]
}
else if (index === length - 1) {
// Last message.
children = [
renderMessageComponent(onComponentDidMount),
<div key={uniqueId()} className="bl-padding"></div>
]
}
else {
// Message in the middle.
children = [
renderMessageComponent()
]
}
return itemComponentRender(children)
}
render() {
const {
chat: propsChat, isChatLoading,
currentUser
} = this.props
const chat = chatSelector(propsChat, currentUser)
const chatHasMessages = chat && !isEmpty(chat.messages)
return (
<div className="bl-order-chat">
<div className="bl-order-chat-header">
// ...
</div>
<div className="bl-order-chat-content">
{
(chatHasMessages &&
<div className="bl-order-chat-content-inner">
<div className="bl-order-chat-infinite-scroll">
<BlSimpleInfiniteScroll items={chat.messages}
ref={this.infiniteScrollComponentRef}
initialId={() => lastOfArray(chat.messages).id}
itemRenderer={(id, i) => this.messageRenderer(id, i, chat.messages)}
loadingComponent={<BlLoadingSpinnerContainer />}
isInfiniteLoading={isChatLoading}
displayInverse
infiniteLoadBeginEdgeOffset={void 0}
infiniteLoadingBeginBottomOffset={void 0}
onInfiniteLoad={() => this.props.onLoadPreviousChatMessages(chat.id)}
onInfiniteScrollMouseEnter={this.handleInfiniteScrollMouseEnter}
onInfiniteScrollMouseLeave={this.handleInfiniteScrollMouseLeave} />
</div>
</div>
)
||
(isChatLoading &&
<BlLoadingSpinnerContainer />
)
}
</div>
<div className="bl-order-chat-footer">
// ...
</div>
</div>
)
}
}
BlOrderChatBox, contains BlOrderChat:
import React from 'react'
import BlOrderChat from './BlOrderChat';
import BlAlert from '../../core/alert/BlAlert';
import BlLoadingSpinnerContainer from '../../core/animation/loading/BlLoadingSpinnerContainer';
export default class BlOrderChatBox extends React.Component {
constructor(props) {
super(props)
this.node = React.createRef()
}
render() {
const {
ordId, currentChat,
isCurrentChatLoading, currentUser,
err
} = this.props
return (
<div className="bl-order-chat-box" ref={this.node}>
<div className="bl-order-chat-box-inner">
{
(err &&
<BlAlert type="error" message={err} />)
||
(currentChat && (
// ...
<div className="bl-order-chat-box-inner-chat-content">
<BlOrderChat ordId={ordId}
chat={currentChat}
isChatLoading={isCurrentChatLoading}
onLoadPreviousChatMessages={this.props.onLoadPreviousChatMessages}
currentUser={currentUser} />
</div>
))
||
<BlLoadingSpinnerContainer />
}
</div>
</div>
)
}
}
And here is the component which renders BlOrderChatBox (it is the topmost stateful component):
import React from 'react'
import { POSTJSON } from '../../../js/ajax';
import config from '../../../config/config';
import { newEmptyArrayAble, arrayToArrayAbleItemsOrder, arrayAbleItemsOrderToArray, mergeArrayAbles, newArrayAble, firstOfArrayAble, isArrayAble } from '../../../js/data_structures/arrayable';
export default class BlOrderChatApp extends React.Component {
static NEW_CHAT_ID = 0
static MAX_NUMBER_OF_MESSAGES_TO_LOAD_PER_AJAX = 30
constructor(props) {
super(props)
this.currentUser = globals.USER
this.lastHandleSendMessagePromise = Promise.resolve()
this.newMessagesMap = {}
this.typingUsersDebouncedMap = {}
// Imagine this comes from a database.
const chat = {
// ...
}
const initialState = {
chats: newArrayAble(this.newChat(chat)),
currentChatId: null,
shouldSelectUserForNewChat: false,
newChatReceivingUsers: newEmptyArrayAble(),
isChatListLoading: false,
isCurrentChatLoading: false,
popoverIsOpen: false,
popoverHasOpened: false,
err: void 0,
focusSendMessageTextarea: false,
newChatsIdsMap: {},
currentChatAuthActs: {},
BlOrderChatComponent: null,
}
this.state = initialState
this.handleLoadPreviousChatMessages = this.handleLoadPreviousChatMessages.bind(this)
}
POST(jsonData, callback) {
let requestJSONData
if (typeof jsonData === "string") {
requestJSONData = {
action: jsonData
}
}
else {
requestJSONData = jsonData
}
return POSTJSON(config.ORDER_CHAT_ENDPOINT_URI, {
...requestJSONData,
order_chat_type: this.props.orderChatType,
}).then(response => response.json()).then(json => {
this.POSTResponseData(json, callback)
})
}
POSTResponseData(data, callback) {
if (data.err) {
this.setState({
err: data.err
})
}
else {
callback && callback(data)
}
}
newChat(chat) {
const newChat = {
id: (chat && chat.id) || BlOrderChatApp.NEW_CHAT_ID,
ord_id: this.props.ordId,
users: (chat && chat.users && (isArrayAble(chat.users) ? chat.users : arrayToArrayAbleItemsOrder(chat.users))) || newEmptyArrayAble(),
messages: (chat && chat.messages && (isArrayAble(chat.messages) ? chat.messages : arrayToArrayAbleItemsOrder(chat.messages))) || newEmptyArrayAble(),
first_message_id: (chat && chat.first_message_id) || null,
typing_users_ids_map: (chat && chat.typing_users_ids_map) || {},
}
return newChat
}
isChatNew(chat) {
return (
chat
&&
(chat.id == BlOrderChatApp.NEW_CHAT_ID || this.state.newChatsIdsMap[chat.id])
)
}
loadPreviousChatMessages(chatId, lowestMessageIdOrNull, makeChatIdCurrent) {
this.POST({
act: 'loadPreviousChatMessages',
chat_id: chatId,
lowest_message_id: lowestMessageIdOrNull,
max_number_of_messages_to_load: BlOrderChatApp.MAX_NUMBER_OF_MESSAGES_TO_LOAD_PER_AJAX
}, json => {
this.setState(prevState => {
const chat = prevState.chats.items[chatId]
const messages = arrayToArrayAbleItemsOrder(json.messages)
const newChat = {
...chat,
messages: mergeArrayAbles(messages, chat.messages)
}
const chats = mergeArrayAbles(prevState.chats, newArrayAble(newChat))
return {
...(makeChatIdCurrent ?
{
currentChatId: chatId,
focusSendMessageTextarea: true,
}
:
{
currentChatId: prevState.currentChatId,
}
),
chats,
isCurrentChatLoading: false,
}
})
})
}
loadPreviousChatMessagesIfNotAllLoaded(chatId) {
let lowestMessageIdOrNull
const chat = this.state.chats.items[chatId]
if (
!this.isChatNew(chat)
&&
(lowestMessageIdOrNull = (chat.messages.order.length && firstOfArrayAble(chat.messages).id) || null)
&&
lowestMessageIdOrNull != chat.first_message_id
) {
this.setState({
isCurrentChatLoading: true
}, () => {
this.loadPreviousChatMessages(chat.id, lowestMessageIdOrNull)
})
}
}
handleLoadPreviousChatMessages(chatId) {
this.loadPreviousChatMessagesIfNotAllLoaded(chatId)
}
// ...
render() {
const currentChat = this.state.chats.items[this.state.currentChatId] || null
const err = this.state.err
return (
<div className="bl-order-chat-app">
<BlOrderChatBox currentUser={this.currentUser}
chats={arrayAbleItemsOrderToArray(this.state.chats)}
currentChat={currentChat}
isCurrentChatLoading={this.state.isCurrentChatLoading}
onLoadPreviousChatMessages={this.handleLoadPreviousChatMessages}
err={err} />
</div>
)
}
}
I tried to remove all the irrelevant code to simplify the reading. Also here is the file which contains the chatSelector function (normalizes the chat array-able object) and the *ArrayAble* functions (an array-able object to me is basically an object which maps objects through their ids in items and has an order property which keeps the sort):
import { isUndefined, unshiftArray, findIndex } from "../utils";
export function chatSelector(chat, currentUser) {
const newChat = { ...chat }
newChat.messages = arrayAbleItemsOrderToArray(chat.messages).sort((a, b) => {
const sortByUnixTs = a.sent_unix_ts - b.sent_unix_ts
if (sortByUnixTs == 0) {
return a.id - b.id
}
return sortByUnixTs
})
newChat.users = arrayAbleItemsOrderToArray(chat.users).filter(user => user.id != currentUser.id)
return newChat
}
/**
* Given an array-able object, returns its array representation using an order property.
* This function acts as a selector function.
*
* The array-able object MUST have the following shape:
*
* {
* items: {},
* order: []
* }
*
* Where "items" is the object containing the elements of the array mapped by values found in "order"
* in order.
*
* #see https://medium.com/javascript-in-plain-english/https-medium-com-javascript-in-plain-english-why-you-should-use-an-object-not-an-array-for-lists-bee4a1fbc8bd
* #see https://medium.com/#antonytuft/maybe-you-would-do-something-like-this-a1ab7f436808
*
* #param {Object} obj An object.
* #param {Object} obj.items The items of the object mapped by keys.
* #param {Array} obj.order The ordered keys.
* #return {Array} The ordered array representation of the given object.
*/
export function arrayAbleItemsOrderToArray(obj) {
const ret = []
for (const key of obj.order) {
if (!isUndefined(obj.items[key])) {
ret[ret.length] = obj.items[key]
}
}
return ret
}
export function arrayToArrayAbleItemsOrder(array, keyProp = "id") {
const obj = newEmptyArrayAble()
for (const elem of array) {
const key = elem[keyProp]
obj.items[key] = elem
obj.order[obj.order.length] = key
}
return obj
}
export function newEmptyArrayAble() {
return {
items: {},
order: []
}
}
export function isEmptyArrayAble(arrayAbleObj) {
return !arrayAbleObj.order.length
}
export function mergeArrayAbles(arrayAbleObj1, arrayAbleObj2, prependObj2 = false) {
const obj = newEmptyArrayAble()
for (const key of arrayAbleObj1.order) {
if (isUndefined(arrayAbleObj1.items[key])) {
continue
}
obj.items[key] = arrayAbleObj1.items[key]
obj.order[obj.order.length] = key
}
for (const key of arrayAbleObj2.order) {
if (isUndefined(arrayAbleObj2.items[key])) {
continue
}
if (!(key in obj.items)) {
if (!prependObj2) {
// Default.
obj.order[obj.order.length] = key
}
else {
unshiftArray(obj.order, key)
}
}
obj.items[key] = arrayAbleObj2.items[key]
}
return obj
}
export function newArrayAble(initialItem = void 0, keyProp = "id") {
const arrayAble = newEmptyArrayAble()
if (initialItem) {
arrayAble.items[initialItem[keyProp]] = initialItem
arrayAble.order[arrayAble.order.length] = initialItem[keyProp]
}
return arrayAble
}
export function lastOfArrayAble(obj) {
return (
(
obj.order.length
&&
obj.items[obj.order[obj.order.length - 1]]
)
||
void 0
)
}
Thank you for your help. If there's something missing which I should have included, please, let me know!
UPDATE: Thanks to Sultan H. it has improved, though the scroll still blocks as soon as I get the reply from the server. See it here: https://streamable.com/3nzu0
Any idea on how to improve this behaviour further?
Thanks!
Here is an attempt to resolve the performance issue, it's not preferrable to do tasks inside the Arrow Function that calculates the new state, in this case, at loadPreviousChatMessages you are calculating stuff in the callback, which may yeild to a load while setting the state on that context.
Preferrable Changes, replace this.setState inside your function with this code, all I've done here is clear the context by moving all the tasks out:
const chat = this.state.chats.items[chatId];
const messages = arrayToArrayAbleItemsOrder(json.messages);
const newChat = {
...chat,
messages: mergeArrayAbles(messages, chat.messages);
}
const chats = mergeArrayAbles(prevState.chats, newArrayAble(newChat));
const newState = {
...(
makeChatIdCurrent ?
{
currentChatId: chatId,
focusSendMessageTextarea: true,
}
:
{
currentChatId: this.state.currentChatId,
}
),
chats,
isCurrentChatLoading: false,
};
this.setState(() => newState);
If that doesn't entirely solve the issue, can you tell if there was at least an improvment?

Setting React key prop to dynamic components array after instantiating

I have a method that returns an array of components that can be comletely different:
renderComponents() {
const children = [];
children.push(this.renderComponent1());
children.push(this.renderComponent2());
if (something) {
children.push(this.renderComponent3());
}
return children;
}
But of course I'm getting an error Each child in an array or iterator should have a unique "key" prop.. I've tried to set key like this:
children.forEach((child, i) => {
Object.defineProperty(child.props, 'key', { value: i });
});
But as it turns out React prevents extension of props so I've received Cannot define property key, object is not extensible.
So my question is next: is it possible to set key prop to each component in an array after instantiating of those components?
UPD: The real code is next (it renders a pagination with ranges like this [1]...[5][6][7][8][9]...[100]):
renderPaginationButton(page) {
const { query, currentPage } = this.props;
return (
<Link
className={classNames(styles.link, { [styles.active]: page === currentPage })}
to={routes.searchUrl({ ...query, page })}
>
{page}
</Link>
);
}
renderPaginationSeparator() {
return (
<div className={styles.separator}>...</div>
);
}
renderPaginationRange(from, amount) {
const { pagesCount } = this.props;
const result = [];
for (let i = Math.max(from, 1); i < Math.min(from + amount, pagesCount); i++) {
result.push(this.renderPaginationButton(i));
}
return result;
}
renderPagination() {
const { currentPage, pagesCount } = this.props;
if (pagesCount <= 1) {
return;
}
const children = this.renderPaginationRange(currentPage - 2, 5);
if (currentPage > 4) {
children.unshift(
this.renderPaginationButton(1),
this.renderPaginationSeparator()
);
}
if (pagesCount - currentPage > 4) {
children.push(
this.renderPaginationSeparator(),
this.renderPaginationButton(pagesCount)
);
}
return (
<div className={styles.pagination}>
{children}
</div>
);
}
To answer your question directly, you can use React.cloneElement to add props onto an already instantiated component.
But that's not what you should do in this case.
In your case, you should have renderPaginationButton() to return a <Link> element with key= prop already put in.

How can you test functions and variables within your react component's render function?

I'm trying to improve my test coverage for my react components, but I am having trouble testing variables and functions declared within the render method of my components. Below are a couple of examples that I'm unable to get covered:
1)
cityStateZip = `${cityStateZip} - ${location.zipExtension}`;
2)
directionsUrl = `maps://maps.apple.com/?saddr=My+Location&daddr=${gpsCoords.lat}+${gpsCoords.lng}`;
3)
const onClick = (pricingTileId) => {
if (store.selectedPharmacy !== pricingTileId) {
store.setPharmacy(pricingTileId);
}
};
Here's the code:
class Tile extends Component {
const { location, store } = this.props;
render() {
let directionsUrl = `https://maps.google.com/?saddr=My+Location&daddr=${gpsCoords.lat}+${gpsCoords.lng}`;
if (navigator.platform.indexOf('iPhone') !== -1
|| navigator.platform.indexOf('iPod') !== -1
|| navigator.platform.indexOf('iPad') !== -1) {
directionsUrl = `maps://maps.apple.com/?saddr=My+Location&daddr=${gpsCoords.lat}+${gpsCoords.lng}`;
}
let cityStateZip = `${location.city}, ${location.state} ${location.zip}`;
if (location.zipExtension) {
cityStateZip = `${cityStateZip} - ${location.zipExtension}`;
}
const onClick = (pricingTileId) => {
if (store.selectedLocation !== pricingTileId) {
store.setLocation(pricingTileId);
}
};
let selectedClass;
if (store.selectedLocation === id) {
selectedClass = 'selected';
}
return (
)
Is there an effective way to test the variables and functions declared in the render function that I'm overlooking? (I'm using Jest and Enzyme for my testing). Thank you!
You can refactor your component like this:
class Tile extends Component {
isMobile = () => {
let mob = navigator.platform
if (mob.indexOf('Iphone')) return true
if (mob.indexOf('Ipad')) return true
if (mob.indexOf('Ipod')) return true
return false
}
isZipValid = () => !!this.props.location.zipExtension
isLocationValid = (id) => this.props.store.location === id
handleClick = (pricingTileId) => {
const { store } = this.props;
if (store.selectedLocation !== pricingTileId) {
store.setLocation(pricingTileId);
}
}
render() {
let directionsUrl
let selectedClass = isLocationValid() && 'selected';
let cityStateZip = `${location.city}, ${location.state} ${location.zip}`;
if (!isMobile()) {
directionsUrl = `maps://maps.apple.com/?saddr=My+Location&daddr=${gpsCoords.lat}+${gpsCoords.lng}`;
}
if (isZipValid()) {
cityStateZip = `${cityStateZip} - ${location.zipExtension}`;
}
return (
<div> Anything</div>
)
}
..
============== PART 2 ==================
You can extract them to a separate file such as lib or helpers
and then import it to your components.
Like this:
Helper:
//helpers.js
export const isMobile = (mob) => {
if (mob.indexOf('Iphone')) return true
if (mob.indexOf('Ipad')) return true
if (mob.indexOf('Ipod')) return true
return false
}
Finally on the component:
export { isMobile } from './helpers'
if(isMobile(navigator.platform)){
//you just abstracted the function
}
Conclusion: your isMobile() can be easily tested from the helpers and supply to any component :)
Now you can easily test function by function
I hope it helped you :D
Kindly,

Categories

Resources