I am using prettier plugin with VS Code for react code indentation.
I am unable to find setting to indent the props param like:
const DataSourceComponent = ({
isOrg,
createTableRowName,
apiUrl,
enableCreateOption,
pageIndexName,
extraHiddenColumns
}) => {
const navigate = useNavigate();
const theme = useTheme();
}
Prettier's indentation look like:
const DataSourceComponent = ({
isOrg,
createTableRowName,
apiUrl,
enableCreateOption,
pageIndexName,
extraHiddenColumns,
}) => {
const navigate = useNavigate();
const theme = useTheme();
}
Is there way to do props param indentation(mentioned in first example) ?
Related
I really do not understand why this is not working, basically, I have a header component with its own context. On the other hand, I have a popOver component that goes inside the header, and this popOver also has its own context.
Now, there is a list of elements that are rendered inside the popOver, the user picks which elements to render, and such list needs to be rendered simultaneously in the header, for that reason I am trying to keep both contexts synchronized, the problem appears when I try to consume the header context inside the popOver context, the values consumed appear to be undefined.
const HeaderContext = createContext();
export const HeaderProvider = ({ children }) => {
const [headChipList, setHeadChipList] = useState([]);
const [isChipOpen, setIsChipOpen] = useState(false);
useEffect(() => {
if (headChipList.length) setIsChipOpen(true);
}, [headChipList]);
return (
<HeaderContext.Provider value={{ headChipList, setHeadChipList, isChipOpen, setIsChipOpen }}>
{children}
</HeaderContext.Provider>
);
};
export const useHeaderContext = () => {
const context = useContext(HeaderContext);
if (!context) throw new Error('useHeaderContext must be used within a HeaderProvider');
return context;
};
As you can see at the end there's a custom hook that allows an easier consumption of the context and also is a safeguard in case the custom hook is called outside context, the popOver context follows this same pattern:
import React, { useState, useContext, createContext, useEffect } from 'react';
import { useHeaderContext } from '(...)/HeaderProvider';
const PopoverContext = createContext();
export const PopoverProvider = ({ children }) => {
const { setHeadChipList, headChipList } = useHeaderContext; // this guys are undefined
const [menuValue, setMenuValue] = useState('Locations with Work Phases');
const [parentId, setParentId] = useState('');
const [chipList, setChipList] = useState([]);
const [locations, setLocations] = useState([]);
useEffect(() => setChipList([...headChipList]), [headChipList]);
useEffect(() => setHeadChipList([...chipList]), [chipList, setHeadChipList]);
return (
<PopoverContext.Provider
value={{
menuValue,
setMenuValue,
chipList,
setChipList,
parentId,
setParentId,
locations,
setLocations
}}
>
{children}
</PopoverContext.Provider>
);
};
export const usePopover = () => {
const context = useContext(PopoverContext);
if (!context) throw new Error('usePopover must be used within a PopoverProvider');
return context;
};
I would really appreciate any highlight about this error, hopefully, I will be able to learn how to avoid this type of error in the future
You're not calling the useHeaderContext function. In PopoverProvider, change the line to
const { setHeadChipList, headChipList } = useHeaderContext();
I'm working on a new major release for react-xarrows, and I came up with some messy situation.
It's not going to be simple to explain, so let's start with visualization:
consider the next example - 2 draggable boxes with an arrow drawn between them, and a wrapping context around them.
focused code:
<Xwrapper>
<DraggableBox box={box} />
<DraggableBox box={box2} />
<Xarrow start={'box1'} end={'box2'} {...xarrowProps} />
</Xwrapper>
Xwrapper is the context, DraggableBox and Xarrow are, well, you can guess.
My goal
I want to trigger a render on the arrow, and solely on the arrow, whenever one of the connected boxes renders.
My approach
I want to be able to rerender the arrow from the boxes, so I have to consume 'rerender arrow'(let's call it updateXarrow) function on the boxes, we can use a context and a useContext hook on the boxes to get this function.
I will call XelemContext to the boxes context.
also, I need to consume useContext on Xarrow because I want to cause a render on the arrow whenever I decide.
this must be 2 different contexts(so I could render xarrow solely). one on the boxes to consume 'updateXarrow', and a different context consumed on Xarrow to trigger the reredner.
so how can I pass this function from one context to another? well, I can't without making an infinite loop(or maybe I can but could not figure it out), so I used a local top-level object called updateRef.
// define a global object
const updateRef = { func: null };
const XarrowProvider = ({ children }) => {
// define updateXarrow here
...
// assign to updateRef.func
updateRef.func = updateXarrow;
return <XarrowContext.Provider value={updateXarrow}>{children}</XarrowContext.Provider>;
};
//now updateRef.func is defined because XelemProvider defined later
const XelemProvider = ({ children }) => {
return <XelemContext.Provider value={updateRef.func}>{children}</XelemContext.Provider>;
};
the thing is, that this object is not managed by react, and also, i will need to handle cases where there is multiple instances of Xwrapper, and I'm leaving the realm of React, so i have 2 main questions:
there is a better approach? maybe I can someone achieve my goal without going crazy?
if there is no better option, is this dangerous? I don't want to release a code that will break on edge cases on my lib consumer's apps.
Code
DraggableBox
const DraggableBox = ({ box }) => {
console.log('DraggableBox render', box.id);
const handleDrag = () => {
console.log('onDrag');
updateXarrow();
};
const updateXarrow = useXarrow();
return (
<Draggable onDrag={handleDrag} onStop={handleDrag}>
<div id={box.id} style={{ ...boxStyle, position: 'absolute', left: box.x, top: box.y }}>
{box.id}
</div>
</Draggable>
);
};
useXarrow
import React, { useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { XelemContext } from './Xwrapper';
const useXarrow = () => {
const [, setRender] = useState({});
const reRender = () => setRender({});
const updateXarrow = useContext(XelemContext);
useLayoutEffect(() => {
updateXarrow();
});
return reRender;
};
export default useXarrow;
Xwrapper
import React, { useState } from 'react';
export const XelemContext = React.createContext(null as () => void);
export const XarrowContext = React.createContext(null as () => void);
const updateRef = { func: null };
const XarrowProvider = ({ children }) => {
console.log('XarrowProvider');
const [, setRender] = useState({});
const updateXarrow = () => setRender({});
updateRef.func = updateXarrow;
return <XarrowContext.Provider value={updateXarrow}>{children}</XarrowContext.Provider>;
};
const XelemProvider = ({ children }) => {
console.log('XelemProvider');
return <XelemContext.Provider value={updateRef.func}>{children}</XelemContext.Provider>;
};
const Xwrapper = ({ children }) => {
console.log('Xwrapper');
return (
<XarrowProvider>
<XelemProvider>{children}</XelemProvider>
</XarrowProvider>
);
};
export default Xwrapper;
const Xarrow: React.FC<xarrowPropsType> = (props: xarrowPropsType) => {
useContext(XarrowContext);
const svgRef = useRef(null);
....(more 1100 lines of code)
logs
I left some logs.
on drag event of a single box you will get:
onDrag
DraggableBox render box2
XarrowProvider
xarrow
Note
currently, this is working as expected.
Update
after many hours of testing, this seems to work perfectly fine. I manage my own object that remember the update function for each Xwrapper instance, and this breaks the dependency between the 2 contexts. I will leave this post in case someone else will also come across this issue.
Update (bad one)
this architecture breaks on react-trees with <React.StrictMode>...</React.StrictMode> :cry:
any idea why? any other ideas ?
just in case someone would need something similar: here's a version that will work even with react strictmode(basically being rellyed of effect which called once and not renders):
import React, { FC, useEffect, useRef, useState } from 'react';
export const XelemContext = React.createContext(null as () => void);
export const XarrowContext = React.createContext(null as () => void);
// will hold a object of ids:references to updateXarrow functions of different Xwrapper instances over time
const updateRef = {};
let updateRefCount = 0;
const XarrowProvider: FC<{ instanceCount: React.MutableRefObject<number> }> = ({ children, instanceCount }) => {
const [, setRender] = useState({});
const updateXarrow = () => setRender({});
useEffect(() => {
instanceCount.current = updateRefCount; // so this instance would know what is id
updateRef[instanceCount.current] = updateXarrow;
}, []);
// log('XarrowProvider', updateRefCount);
return <XarrowContext.Provider value={updateXarrow}>{children}</XarrowContext.Provider>;
};
// renders only once and should always provide the right update function
const XelemProvider = ({ children, instanceCount }) => {
return <XelemContext.Provider value={updateRef[instanceCount.current]}>{children}</XelemContext.Provider>;
};
const Xwrapper = ({ children }) => {
console.log('wrapper here!');
const instanceCount = useRef(updateRefCount);
const [, setRender] = useState({});
useEffect(() => {
updateRefCount++;
setRender({});
return () => {
delete updateRef[instanceCount.current];
};
}, []);
return (
<XelemProvider instanceCount={instanceCount}>
<XarrowProvider instanceCount={instanceCount}>{children}</XarrowProvider>
</XelemProvider>
);
};
export default Xwrapper;
I have a little upload handler like this:
const handleUploadPhoto = filename => {
setHasImage('has-image');
setPostButtonState('');
onAddedPhoto(filename);
setPostImageFilename(filename);
};
I use it all over the place and I'd love to export it from a helpers.js file and import it wherever needed, but I'm not sure how to do that considering when the useState variables affected by it need to stay in the parent, not the imported helper.
const [postImageId, setPostImageId] = useState(null);
const [postImageFilename, setPostImageFilename] = useState(null);
const [postImageUrl, setPostImageUrl] = useState(null);
Is this kind of function just not a good candidate for export / import?
One option is to make your own hook that defines all of the state setters and takes the onAddedPhoto as a parameter:
const useImageStuff = (onAddedPhoto) => {
const [hasImage, setHasImage] = useState('');
const [postButtonState, setPostButtonState] = useState('');
const [postImageFilename, setPostImageFilename] = useState('');
const handleUploadPhoto = () => {
setHasImage('has-image');
setPostButtonState('');
onAddedPhoto(filename);
setPostImageFilename(filename);
};
return {
hasImage,
setHasImage,
postButtonState,
setPostButtonState,
postImageFilename,
setPostImageFilename,
handleUploadPhoto,
};
Then use that all over the place:
const SomeComponent = () => {
const onAddedPhoto = () => {
// ...
};
const {
hasImage,
setHasImage,
postButtonState,
setPostButtonState,
postImageFilename,
setPostImageFilename,
handleUploadPhoto,
} = useImageStuff(onAddedPhoto);
// ...
I'm learning React with Hooks and context. Learning by making a simple CRUD app. I have functions that allow me to ADD notes, DELETE notes, Filter if important, Toggle importance in some Context. So far so good.
However I'm stuck on how I would be able to edit my note. I've searched online and every react hooks CRUD tutorial seems to just be add and delete.
My functions for a CRUD note taking app below.
import React, { createContext, useState, useEffect } from 'react';
import uuid from 'uuid/v1';
export const NotesContext = createContext();
const NotesContextProvider = (props) => {
const [notes, setNotes] = useState([]);
const [showAll, setShowAll] = useState(true);
const notesToShow = showAll ? notes : notes.filter((note) => note.important);
//CRUD operations
// Create
const addNote = (content) => {
setNotes([
...notes,
{
content,
id: uuid(),
important: false
}
]);
};
// Update
const toggleImportance = (noteId) => {
const updatedNotes = notes.map((note) =>
note.id === noteId ? { ...note, important: !note.important } : note
);
setNotes(updatedNotes);
};
// Delete
const removeNote = (id) => {
setNotes(notes.filter((note) => note.id !== id));
};
// Get any notes stored in local storage
useEffect(() => {
const data = localStorage.getItem('notes');
if (data) {
setNotes(JSON.parse(data));
}
}, []);
// save notes to local storage
useEffect(() => {
localStorage.setItem('notes', JSON.stringify(notes));
}, [notes]);
return (
<NotesContext.Provider
value={{
addNote,
removeNote,
notes,
showAll,
setShowAll,
notesToShow,
toggleImportance
}}>
{props.children}
</NotesContext.Provider>
);
};
export default NotesContextProvider;
I'm hoping to have an onClick on an edit button on my note/todo and it'll allow me to update the note/todo.
Thanks any guidance would be appreciated.
I have a react component. I want to set the state within this component that will be passed down to child components. I am getting a reference error to this and I am not sure why.
export const WidgetToolbar: React.FC<{}> = () => {
this.state = {
targetBox:null,
}
const isOpen = useBehavior(mainStore.isWidgetToolbarOpen);
const themeClass = useBehavior(mainStore.themeClass);
const userDashboards = useBehavior(dashboardStore.userDashboards);
const [filter, setFilter] = useState("");
const [sortOrder, setSortOrder] = useState<SortOrder>("asc");
const userWidgets = useMemo(() => {
let _userWidgets = values(userDashboards.widgets).filter((w) => w.widget.isVisible);
if (sortOrder === "asc") {
_userWidgets.sort((a, b) => a.widget.title.localeCompare(b.widget.title));
} else {
_userWidgets.sort((a, b) => b.widget.title.localeCompare(a.widget.title));
}
if (!isBlank(filter)) {
_userWidgets = _userWidgets.filter((row) => {
return row.widget.title.toLowerCase().includes(filter.toLocaleLowerCase());
});
}
return _userWidgets;
}, [userDashboards, sortOrder, filter]);
...
This is the error I am getting:
TypeError: Cannot set property 'state' of undefined
at WidgetToolbar (WidgetToolbar.tsx?ba4c:25)
at ProxyFacade (react-hot-loader.development.js?439b:757)
There's no this or this.state in a functional component. Use the useState hook, similar to what you're doing a few lines below.
export const WidgetToolbar: React.FC<{}> = () => {
const [targetBox, setTargetBox] = useState<null | whateverTheTypeIs>(null);
//...
}
Functional React Components can't have state. You'd have to use a class-based component in order to have state.
https://guide.freecodecamp.org/react-native/functional-vs-class-components/
You used the hook to "use state" in this function: const [filter, setFilter] = useState("");
You could do the same for targetBox, instead of trying to set a property on a non-existent 'this'