Is it possible to save components state when they are stored in an array manipulated? - reactjs

I'm trying to create a stepper form
I store my steps in an array of json with a proprety component ({typeOfComponent, component, key})
It works wells, but:
Everytime i slice my array, like when i move up/down a step or add a new step between two steps.
I lose the states inside my component.
I tried to use memo, i don't understand why it's only when an item position my composent is recreate. Is it possible like a pointer in C to store only his "adress"
the code sandbox exemple =>
https://codesandbox.io/s/infallible-maxwell-zkwbm?file=/src/App.js
In my real projet, the button ADD is a button for chosing the new step type
Is there any solution for manipulates my steps without losing the user data inside ?
Thanks for your help

React is re-mounting the components inside of this every re-render probably due to a variety of reasons. I couldn't get it to work as is, but by lifting the state up from your components, it will work.
You'd likely need to lift the state up anyway because the data isn't where you need it to be to make any use of your form when the user is done with it.
In order to lift the state up, I added the current value to the steps array:
function addNext(step, index) {
componentKey++;
setSteps(prevState => {
let newState = [...prevState];
step = 1;
newState.splice(index + 1, 0, {
stepNumber: step,
component: getStepContent(step, componentKey),
value: getDefaultValue(step),
key: componentKey
});
return newState;
});
}
I also made sure your getStepContent just returned the component rather than a node so you can render it like this:
<step.component
value={step.value}
onChange={handleChange}
data-index={i}
/>
There are definitely a lot of ways to optimize this if you start running into performance issues, of course.
https://codesandbox.io/s/beautiful-river-2jltr?file=/src/App.js

Related

Reusing components in react and telling the component which key: value of a state to change

I'm having a little bit of difficulty figuring out how to reuse components in many places.
Obviously the reason why react is so good is because you can create common components and reuse them across many different pages, or just multiple times in the same page.
I have this component for displaying a dropdown that a user can use to select a new value, and change their settings. This component is reused in many different places on my website.
<ChannelSelect
channelID={
saveEnabled.saveEnabled.newSettings.verificationPanel.channelID
}
settings={
saveEnabled.saveEnabled.newSettings.verificationPanel.channelID
}
/>
What I am struggling with is telling this component which key: value in the state (object) to change. This is because simply passing in the code below, doesn't actually allow me to change the state of this specific key.
settings={saveEnabled.saveEnabled.newSettings.verificationPanel.channelID}
In my select menus onChange event I have the code snippet below. However, this doesn't actually allow me to change the specific value declare, it would actually just overwrite the whole object.
const { saveEnabled, setSaveEnabled } = useContext(SaveContext);
const onChange = (event) => {
props.settings = "newValue"
setSaveEnabled(props.settings)
Any idea how I can do this?

How to obtain a value from a file in another file thanks to the store

I have recently started a project in a team of three people. We've been learning some React for that, and when I explained to a friend what I was trying to do, he advised me to try it with Redux, but I'm not quite sure how I'm supposed to proceed.
My goal is to generate a code in an Arrival.js page, depending on a form that the customer filled, based on his first name and the date. I have the right function to generate that code. Now when the customer submits the form, a pop-up shows up, telling him "here's your code: CODE1245" for example. The thing is that this pop-up is a component located in another file named PopUpArrival.js and I can't manage to transfer the code generated in Arrival.js with the form's information.
So I tried to set up a store with reducers and actions, but I can't manage to find any actions that would fit my goals. Am I overthinking it by trying to use Redux? Or is there an easy way to do so? It's been three days and I'm quite lost and demotivated to be honest. Thanks if anyone took the time to read me and I'd be even more grateful if anyone shows up with a solution
If your components have a
parent-child relationship, then it would be easy to send the code as a prop to the child.
Sibling relationship, then What is the most simplest method of updating component's state from another component? Lets say components are siblings?
Not related at all, there are a lot of ways like cookies, local storage, context, redux, etc.
I guess using redux only for this purpose might be overkill. You can look at contexts in that case.
I think Redux maybe an overkill here. You can get this done without redux from how it looks. If you can consider the following flow.
Your Arrival.js will maintain state for the first name and the date. Your PopUpArrival.js should be a component in itself, which takes whatever text you want to show in popup as a prop. Based on when you want to trigger the popup logic, you should display the PopUpArrival component. I have tried to roughly write some code below which does the same.
const PopUpArrival = (props) => {
const { textToShow } = props;
return(
<div>{textToShow}</div>;
);
}
const Arrival = () => {
// maintains state for both name and date
const [showPopup, setPopupDisplay] = useState(false);
const togglePopup = () => {
setPopupDisplay((currentDisplay) => !currentDisplay);
}
const getTextToShow = () => {
return `${name}-{date}`; // whatever logic you have
}
return(
<>
<button onClick={togglePopup}>
Submit
</button>
{
showPopup && <PopUpArrival textToShow={getTextToShow()}/>
}
</>
)
}

useMemo on useState with Array and many Object

My apps run although its kind of slow since I loop to create button and loop again to change the color of the button
Its slow because every time I change a color in a button I have to loop in useState array of objects
My question is, how do I only render one object in an Array that uses useState ?
Or.. is there any faster way / better way than looping like this ?
I also try to target the checked status with booleanMonth[0].checked=true which change the status without looping but it doesn't change the color.
this is the array:
const [booleanMonth,setMonth]=useState([
{key:0,value:'January',title:'Jan',color:'black',checked:false},
{key:1,value:'February',title:'Feb',color:'black',checked:false},
{key:2,value:'March',title:'Mar',color:'black',checked:false},
{key:3,value:'April',title:'Apr',color:'black',checked:false},
{key:4,value:'May',title:'May',color:'black',checked:false},
{key:5,value:'June',title:'Jun',color:'black',checked:false},
{key:6,value:'July',title:'Jul',color:'black',checked:false},
{key:7,value:'August',title:'Aug',color:'black',checked:false},
{key:8,value:'September',title:'Sep',color:'black',checked:false},
{key:9,value:'October',title:'Oct',color:'black',checked:false},
{key:10,value:'November',title:'Nov',color:'black',checked:false},
{key:11,value:'December',title:'Dec',color:'black',checked:false}
])
this is where I create buttons which will loop if one of the object in array ABOVE changed because I pressed a button :
const createButtonMonth = useMemo(() =>{
console.log('createButtonMonth')
return (<View style={styles.containerForButtons2}>
{
booleanMonth.map((item,key) =>
<View key={item.key} style={styles.buttonFilter3}>
<Button style={styles.buttonFilter3}
title={item.title}
value={item.checked}
onCheckColor='red'
color={item.checked==true ? 'green':'black'}
onPress={()=>onPressMonthFilter(booleanMonth[item.key].key,booleanMonth[item.key].checked)}
/></View>)
}
</View>)
},[booleanMonth])
this is the press button function which also loop to determine which button to change its color because its checked status true / false (I think this slows me down also because of the loop)
const onPressMonthFilter = (keyMonth,statusMonth) =>{
let newArr = [...booleanMonth]
if(newArr[keyMonth].checked==false){
newArr[keyMonth].checked=true
}else{
newArr[keyMonth].checked=false
}
setMonth(newArr)
}
open for any suggestion :< help newbie here please
The only thing I can think of to further enhance this is to wrap onPressMonthFilter with useCallback
const onPressMonthFilter = useCallback((keyMonth,statusMonth) =>{
let newArr = [...booleanMonth]
if(newArr[keyMonth].checked==false){
newArr[keyMonth].checked=true
}else{
newArr[keyMonth].checked=false
}
setMonth(newArr)
}, [setMonth, booleanMonth])
So the function will return a memoized value. Other than that the code seems to be pretty straight forward, and you don't really have any choice but to loop them to assign the UI.
looping on the array that small shouldn't slow down the app tho, unless you have thousands of data on the array.
I suggest keeping the static data static and only the application state in the state. From a record perspective I know it makes sense to have all the attributes for an entity together but it but in this case I think you can just manage the state of the buttons and infer everything else. For instance, you can infer the color of the button if you know whether it is checked or not.
You can have a list of months as an static array to generate your UI. Then keep array state to keep track of buttons that are checked. If the value in the button is present in the state then button should be checked. If the button is checked then the color should be green. The action of the button will simply add its value to the state array if missing or remove it if exists.
Please review this example showcasing the suggestions
https://codesandbox.io/s/elated-bose-0vwtw

Create and Read State for thousands of items using Recoil

I've just started using Recoil on a new project and I'm not sure if there is a better way to accomplish this.
My app is an interface to basically edit a JSON file containing an array of objects. It reads the file in, groups the objects based on a specific property into tabs, and then a user can navigate the tabs, see the few hundred values per tab, make changes and then save the changes.
I'm using recoil because it allows me to access the state of each input from anywhere in my app, which makes saving much easier - in theory...
In order to generate State for each object in the JSON file, I've created an component that returns null and I map over the initial array, create the component, which creates Recoil state using an AtomFamily, and then also saves the ID to another piece of Recoil state so I can keep a list of everything.
Question 1 Is these a better way to do this? The null component doesn't feel right, but storing the whole array in a single piece of state causes a re-render of everything on every keypress.
To Save the data, I have a button which calls a function. That function just needs to get the ID's, loop through them, get the state of each one, and push them into an Array. I've done this with a Selector too, but the issue is that I can't call getRecoilValue from a function because of the Rules of Hooks - but if I make the value available to the parent component, it again slows everything right down.
Question 2 I'm pretty sure I'm missing the right way to think about storing state and using hooks, but I haven't found any samples for this particular use case - needing to generate the state up front, and then accessing it all again on Save. Any guidance?
Question 1
Get accustomed to null-rendering components, you almost can't avoid them with Recoil and, more in general, this hooks-first React world 😉
About the useRecoilValue inside a function: you're right, you should leverage useRecoilCallback for that kind of task. With useRecoilCallback you have a central point where you can get and set whatever you want at once. Take a look at this working CodeSandbox where I tried to replicate (the most minimal way) your use-case. The SaveData component (a dedicated component is not necessary, you could just expose the Recoil callback without creating an ad-hoc component) is the following
const SaveData = () => {
const saveData = useRecoilCallback(({ snapshot }) => async () => {
const ids = await snapshot.getPromise(carIds);
for (const carId of ids) {
const car = await snapshot.getPromise(cars(carId));
const carIndex = db.findIndex(({ id }) => id === carId);
db[carIndex] = car;
}
console.log("Data saved, new `db` is");
console.log(JSON.stringify(db, null, 2));
});
return <button onClick={saveData}>Save data</button>;
};
as you can see:
it retrieves all the ids through const ids = await snapshot.getPromise(carIds);
it uses the ids to retrieve all the cars from the atom family const car = await snapshot.getPromise(cars(carId));
All of that in a central point, without hooks and without subscribing the component to atoms updates.
Question 2
There are a few approaches for your use case:
creating empty atoms when the app starts, updating them, and saving them in the end. It's what my CodeSandbox does
doing the same but initializing the atoms through RecoilRoot' initialState prop
being updated by Recoil about every atom change. This is possible with useRecoilTransactionObserver but please, note that it's currently marked as unstable. A new way to do the same will be available soon (I guess) but at the moment it's the only solution
The latter is the "smarter" approach but it really depends on your use case, it's up to you to think if you really want to update the JSON at every atom' update 😉
I hope it helps, let me know if I missed something 😊

Avoid re-rendering a big list of items with react-redux

I am using redux with react and typescript for my application. I am working with many items used at different places of my app. My state looks like this:
{
items: {42: {}, 53: {}, ... }, //A large dictionary of items
itemPage1: {
itemsId: [ 42, 34, 4 ],
...
},
itemPage2: { ...
},
...
}
The user can modify some attributes of the items dispatching some actions. When this happen I need to redraw the components that have been modified in each pages. The issue is that my items are quite big and I cant afford to redraw all of them at each small modification. I was wondering is this approach would work:
I have a fist component <ItemPage1> which connects to the store to get all of the states stored in the tree under itemPage1 e.g. the list of items id: itemsId.
Inside <ItemPage1>, I loop over the itemsId property to generate multiple FilterItem components: itemsId.map( itemId => return <FilterItem id=itemId>);
Finally each Item is connected using ownProps to get the correct part of the state:
const mapStateToItemProps = (state, ownProps) => {
return {
item: state.items[ownProps.id],
}
}
const mapDispatchToItemProps = (dispatch, ownProps) => {
return null;
}
const FilterItem = connect(
mapStateToItemProps,
mapDispatchToItemProps
)(Item)
Can you confirm or refute that if I update the item of id 42, then only this item is going to be re-rendered ?
When rendering big list you need to take into considerations few things :
Lower the total number of DOM elements that you need to render (by not rendering items that are not actually visible on the screen, also known as virtualization)
Don't re-render items that have not changed
Basically, what you want to avoid is a complete re-render of your list (or your page) when the user edits one single row. This can be achieved exactly how you did it, i.e : by passing to the list container only the ids of items that need to be rendered, and to map over these ids to connect each component by using ownProps. If you have a dump <Item/> component, your <ItemPage/> component will create connected connect(<Item/>) component.
This is going to work, if your put a console.log('item rendered') in your <Item/> component class you will notice that there is only one call.
BUT (and it's a big but), what is not obvious when working with react-redux is that all connected components that depends on their ownProps will always rerender if any part of the state change. In your case, even if the <Item/> components will not re-render, their wrapped component connect(Item) will ! If you have few dozens of items, you might encounter some latency if actions need to be dispatched quickly (for example when typing in an input). How to avoid that ? Use a factory function to use ownProps as the initial props :
const mapStateToItemProps = (_, initialProps) => (state) => {
return {
item: state.items[initialProps.id], // we're not relying on the second parameters "ownProps" here, so the wrapper component will not rerender
}
}
const mapDispatchToItemProps = (dispatch, ownProps) => {
return null;
}
const FilterItem = connect(
mapStateToItemProps,
mapDispatchToItemProps
)(Item)
I suggest you to take a look to this other answer.
You might also be interested in these excellent slides : Big List High Performance React & Redux
And finally, you should definitively take a look to react-virtualized to perform the virtualization of your list (i.e, displaying only the item that the user can actually see).
Ok, I've found this discussion: https://github.com/reactjs/redux/issues/1303
At the bottom it is clearly stated (from multiple protagonists):
[...] react-redux takes care of this. It lets you specify specific parts of the state you care about, and takes care to bail out of updating React components when the relevant parts have not changed.
[...] Just wanted to fully understand that what's going on under the hood here, So if the Redux store gets updated but one specific component state hasn't changed, Redux won't trigger the forceUpdate() method for that component? [...]
The wrapper component generated by React-Redux's connect() function does a several checks to try to minimize the number of times your actual component has to re-render. This includes a default implementation of shouldComponentUpdate, and doing shallow equality checks on the props going into your component (including what's returned from mapStateToProps). So yes, as a general rule a connected component will only re-render when the values it's extracting from state have changed.
So I believe my implementation is good, it won't re-render all the items since only one item will see its properties modified.

Resources