How to sort React components based on specific value? - javascript

I have React component. This components take 'units' - (array of objects) prop. Based on that I render component for each of item. I want to sort my components based on 'price' value, which is one of state items property. But when i trigger the sorting - state changes correctly but my components order not changing.
const SearchBoxes = ({units}) => {
const [unitsState, setUnitsState] = useState([])
useEffect(() => {
setUnitsState(units)
}, [units])
const sortByPrice = () => {
const sortedUnits = sort(unitsState).desc(u => u.price); // sorting is correct
setUnitsState(sortedUnits) // state is changing correctly
}
return (
<div>
{unitsState.map((u,i) => {
return <UnitBox key={u.price} unit={u} />
})}
</div>
)
}
Can somebody help me, please ?
Why my components order do not changing when the state is changing after sort triggering ?

You aren't calling sortByPrice anywhere--all you've done is to define the function. I haven't tried it, but what if you changed useEffect to:
useEffect(() => {
setUnitsState(sort(unitsState).desc(u => u.price));
}, [units])
Then you don't need the sort method at all.

Related

React lifting states up and down multiple times to filter components

Component diagram:
"Main"
|--"Side"--"CategoryPicker"
|
|--"ItemBoard"
categoryPicker gets the chosen value.
const filterResultHandler = (e) => {
props.onFilterChange(e.target.value);}
...
onChange={filterResultHandler}
And lift up the value to Side.
const [filterState, setFilterState] = useState("all");
const onFilterChangeHandler = () => { props.onPassData(setFilterState);};
...
<CategoryPicker selected={filterState} onFilterChange={onFilterChangeHandler} />
Then I repeat to lift value to the Main.
(Up to this point I have console.log the value and it seemed OK.)
const [recData, setRecData] = useState("all");
const onFilterChangeHandler = (passedData) => {
setRecData(passedData);};
<Side onPassData={onFilterChangeHandler} selected={recData} />
Then pass it down to Itemboard as a prop.
<ItemBoard items={items} recData={recData} />
In ItemBoard I am trying to filter the array then compare to later map it and display filtered components.
const filteredProducts = props.items.filter((product) => {
return (product.cat.toString() === props.recData)})
{filteredProducts.map((product, index) => (
<Item cat={product.cat} />
))}
Warning: Cannot update a component (Side) while rendering a different component (Main). To locate the bad setState() call inside Main
Where am I loosing my logic?
PS.
Trying to focus on understanding how lifting up and passing props works, not looking for better solutions to the problem right now.
you have the bad setState use in this code:
const [recData, setRecData] = useState("all");
const onFilterChangeHandler = (passedData) => {
setRecData(passedData);};
<Side onPassData={onFilterChangeHandler} selected={recData} />
why you are passing this selected={recData} data again to Side component, you are updating the state of Main component from Side component and passing the selected={recData} again, remove this and try again

Conditionally mapping two different arrays into a React component depending on boolean value

I currently have an array called options which is mapped into a React component like so:
{options.map((option) => (
<Component key={option.code}></Component>
))}
However, I am trying to expand my component so that if a boolean value: shouldCount is true, then the optionsWithCount array is passed to the component instead of the options array. The component above has a lot more props etc than shown so I'd like to avoid just repeating the component with all of its props if possible.
Can anyone suggest a possible way of going about this?
Would using a utils function getOptions() work? It would take in the shouldCount flag as input and return the desired array. Example:
{
getOptions(shouldCount).map((option) => (
<Component key={option.code}></Component>
));
}
const getOptions = (shouldCount) => {
return shouldCount ? optionsWithCount : options;
}
You can update the options variable conditionally so you don't have to rewrite the same code again.
Make options a state;
const [options, setOptions] = useState([])
And use useEffect to update it;
useEffect(()=>{
if(shouldCount) setOptions([1,2,3,4,5])
else setOptions([5,6,7,8,9])
}, [shouldCount])
So that way, when shouldCount changed it will trigger useEffect and change optinos values.

how to prevent re-rendering components with redux

How to prevent component re-rendering, when i have an hierarchical array of objects (array of objects) using redux dispatching and memo
for example i have like this list of list of components
like
Elements =[ // an array in store.state variable
{name='a',
subEelemets:[
{name:'a-a',
components:[
{
name:'a-a-1',
component:'TextFiled',
value:'default value...'
},
]
},
]
},
]
i used redux to update components values inside my Elements array using dispatch but the performance downgrades because of many re-rendering,
i tried with memo to prevent re rendering but it also updates the entire Elements array because i used useSelector,
const ImportedComponent = memo((props) => {
const LoadableComponent = loadable(() =>
import("../lib" + props.compName))
);
return (
<LoadableComponent
{...props}
id={props.id}
/>)},(a,b)=>a.id===b.id?true:false)
here the code how i redner my compoents
const selectTodoIds = state => state.components.map((todo,index) => todo)
const updateComp = () => {
const Components = useSelector(selectCompsIds, shallowEqual)
const renderedListItems = Components.map((CompId) =>
<ImportedComponent key={CompId} elementID={CompId} />
)
return <ul className="todo-list">{renderedListItems}</ul>
}
it works when i used a flat array as presented in the tutorial https://redux.js.org/tutorials/fundamentals/part-5-ui-react but not for hierarchical one, because i should use the "name" to define which subelement i'm updating,
is there any strategy to solve this problem?
ps: the code is just for clarification,
Rather than memo you could try useMemo:
const ImportedComponent = (props) => {
const LoadableComponent = useMemo(() => {
return loadable(() => import("../lib" + props.compName));
},[props.compName]);
...
memo only helps when there's lots of re-renders with the same props, which it doesn't appear you have.
That's a complete shot in the dark, though. Can you post a link to a stackblitz, maybe? It'd be nice to see more of your code in context.

Prevent child state resets on props change

I am currently making a Graph component that fetches data from an API, parses the data to be used with a graph library, and then renders the graph. I have all of that working right now, but the issue I am having is with adding the ability to filter. The filtering I am currently doing is done by the parent of the Graph component, which will set the filters prop in the component which is then processed by a useEffect. But this seems causes some portions to re-render and I am trying to prevent. Below is what I have roughly speaking.
Rough example of Parent:
const Parent = (props) => {
const [filters, setFilters] = useState({});
//there are more state values than just this one also cause
//the same problem when their setState is called.
return (
<Graph filters={filters} />
<FilterComponent
onChange={(value) => setFilters(value)}
/>
)
}
export default Parent
Rough example of Child:
const Graph = (props) => {
const [nodes, setNodes] = useState({});
const [links, setLinks] = useState({});
const [velocity, setVelocity] = useState(0.08);
const createGraph = async () => {
//fetches the data, processes it and then returns it.
//not including this code as it isn't the problem
return {
nodes: nodes,
links: links,
};
}
//loads the graph data on mount
useEffect(() => {
const loadGraph = async () => {
const data = await createGraph();
setNodes(data.nodes);
setLinks(data.links);
};
loadGraph();
}, []);
//filters the graph on props change
useEffect(() => {
//this function uses setNodes/setLinks to update the graph data
filterGraph(props.filter);
}, [props.filters]);
return (
<ForceGraph2D
graphData={{
nodes: nodes,
links: links,
}}
d3VelocityDecay={velocity}
cooldownTicks={300}
onEngineStop={() => setVelocity(1)}
/>
);
}
export default Graph
My main issue is that whenever the FilterComponent updates, while I want it to update the graph data, this seems to re-render the Graph component. This causes the graph to start moving. This graph library creates a graph which kinda explodes out and then settles. The graph has a cooldown of 300, and after which it isn't supposed to move, which is where onEngineStop's function is called. But changing the filter state in Parent causes the graph to regain it's starting velocity and explode out again. I want to be able to change the filter state, update the graph data, without re-rendering it. I've looked into useMemo, but don't know if that's what I should do.
I'm fairly new to React having just started two weeks ago, so any help is greatly appreciated! Also, this is my first post on stackOverflow, so I apologize if I didn't follow some community standards.
Edit
I was asked to include the filterGraph function. The function actually was designed to handle different attributes to filter by. Each node/link has attributes attached to them like "weight" or "size". The filterComponent would then pass the attr and the value range to filter by. If a component falls outside that range it becomes transparent.
const Graph = (props) => {
...
//attr could be something like "weight"
//val could be something like [5,10]
const filterGraph = ({ attr, val }) => {
for (const [id, node] of Object.entries(nodes)) {
const value = nodes[id][attr];
if (val.length == 2) {
if (val[0] > value || val[1] < value) {
const color = nodes[id]["color"] || "#2d94adff";
nodes[id]["color"] = setOpacity(color, 0)
);
} else {
const color = nodes[id]["color"] || "#2d94adff";
nodes[id]["color"] = setOpacity(color, 1)
);
}
}
}
setNodes(Object.values(this.nodes));
}
...
}
In your example you mention that filterGraph uses setNodes/setLinks. So everytime the filter changes (props.filters) you will do 2 setState and 2 rerenders will be triggered. It can be that React will batch them so it will only be 1 rerender.
Depending on what filterGraph does exactly you could consider let it return filteredNodes en filteredLinks without putting the filterGraph in a useEffect.
Then pass the filteredNodes en filteredLinks to the graphData like graphData={{
nodes: filteredNodes,
links: filteredLinks,
}}
This way you won't trigger extra rerenders and the data will be filtered on every render. which is already triggered when the props.filters change. This is an interesting article about deriving state https://kentcdodds.com/blog/dont-sync-state-derive-it
Since you also mention that there are more state values in the parent you could make the component a pure component, which means it won't get rerendered when the parent renders but the props that are being passed don't change
https://reactjs.org/docs/react-api.html#reactmemo
Also it's better to include createGraph in the useEffect it's being used or wrap it in a useCallback so it won't be recreated every render.
const Graph = React.memo((props) => {
const [nodes, setNodes] = useState({});
const [links, setLinks] = useState({});
const [velocity, setVelocity] = useState(0.08);
//loads the graph data on mount
useEffect(() => {
const createGraph = async () => {
//fetches the data, processes it and then returns it.
//not including this code as it isn't the problem
return {
nodes: nodes,
links: links,
};
}
const loadGraph = async () => {
const data = await createGraph();
setNodes(data.nodes);
setLinks(data.links);
};
loadGraph();
}, []);
const { filteredNodes, filteredLinks } = filterGraph(props.filter)
return (
<ForceGraph2D
graphData={{
nodes: filteredNodes,
links: filteredLinks,
}}
d3VelocityDecay={velocity}
cooldownTicks={300}
onEngineStop={() => setVelocity(1)}
/>
);
})
export default Graph

Array is initially empty, but after an entry in a text field which is used for filtering, it is full

I verushc an array from one component to another component.
The initial array is filled by a DB and is not empty.
If I try to map over the array in my second component, it is empty (length = 0);
However, after I wrote a value in a search box to filter the array, all articles appear as intended.
What is that about?
export default function Einkäufe({ alleEinkäufe, ladeAlleEinkäufe, url }) {
const [searchTerm, setSearchTerm] = React.useState("");
const [searchResults, setSearchResults] = React.useState(alleEinkäufe);
const listeFiltern = (event) => {
setSearchTerm(event.target.value);
};
React.useEffect(() => {
setSearchResults(alleEinkäufe);
}, []);
React.useEffect(() => {
const results = alleEinkäufe.filter((eink) =>
eink.artikel.toLowerCase().includes(searchTerm.toLowerCase())
);
setSearchResults(results);
}, [searchTerm]);
[...]
{searchResults.map((artikel, index) => {
return ( ... );
})}
}
The problem is with your useEffect hook that sets the list of searchResults, it's not rerun when alleEinkäufe property is updated. You need to add alleEinkäufe as it's dependency.
React.useEffect(() => {
setSearchResults(alleEinkäufe);
}, [alleEinkäufe]);
My bet is that the parent component that renders Einkäufe is initially passing an empty array which is used as searchResults state and then never updated since useEffect with empty dependencies array is only run once on the component's mount.
I would also advise you to use English variable and function names, especially when you ask for assistance because it helps others to help you.
Your search term intially is "". All effects run when your components mount, including the effect which runs a filter. Initially, it's going to try to match any article to "".
You should include a condition to run your filter.
React.useEffect(() => {
if (searchTerm) {
const results = alleEinkäufe.filter((eink) =>
eink.artikel.toLowerCase().includes(searchTerm.toLowerCase())
);
setSearchResults(results);
}
}, [searchTerm]);
BTW, "" is falsy.

Categories

Resources