Is there a way to do not repeat this loop - javascript

I have a question I am making React app. The thing is that in useEffect I loop through six items every time when only one thing changes. How to solve it to change only one variable which was changed in reducer function not looping for 6 items when only one was changed, or is it okay to keep code like this?
const initialReducerValue = {
name: {
val: '',
isValid: false,
},
lastName: {
vaL: '',
isValid: false
},
phoneNumber: {
val: '',
isValid: false
},
city: {
val: '',
isValid: false,
},
street: {
val: '',
isValid: false
},
postal: {
val: '',
isValid: false
},
}
const OrderForm = () => {
const orderReducer = (state, action) => {
if (action.type === 'HANDLE TEXT CHANGE') {
return {
...state,
[action.field]: {
val: action.payload,
isValid: true
}
}
}
}
const [formState, formDispatch] = useReducer(orderReducer, initialReducerValue)
const [formIsValid, setFormIsValid] = useState(false)
const changeTextHandler = (e) => {
formDispatch({
type: 'HANDLE TEXT CHANGE',
field: e.target.name,
payload: e.target.value
})
}
useEffect(() => {
const validationArray = []
for (const key of Object.keys(formState)) {
validationArray.push(formState[key].isValid)
}
const isTrue = validationArray.every(item => item)
setFormIsValid(isTrue)
}, [formState])

This code
const validationArray = []
for (const key of Object.keys(formState)) {
validationArray.push(formState[key].isValid)
}
const isTrue = validationArray.every(item => item)
is equivalent to
const isTrue = Object.values(formState).every(item => item.isValid);
This still iterates over all items when only one was changed, but with a temporary array less.
For six items, I would not spend time trying to optimize this code further, but that's your choice.

Related

Changing attribute in state React.js

I'm doing Todo App in React and I'd use some help. This is probably trivial question, but I don't know how to do it.
context.js:
const initialState = {
isSidebarOpen: true,
isLoading: false,
isEditing: false,
todos: [
{ id: 1608592490852, todo: "Buy milk", important: false },
{ id: 1608592490939, todo: "Take out trash", important: false },
{ id: 1608634291740, todo: "Buy flowers for mom", important: false },
{ id: 1608634291874, todo: "Repair washing machine", important: false },
],
importantTodos: [{ id: 1608634291874, todo: "Repair washing machine" }],};
const handleAction = (e, item) => {
const { id, todo } = item;
const actionName = e.target.getAttribute("name");
if (actionName === actionTypes.addImportant) {
dispatch({ type: actionTypes.addImportant, payload: id });
}
reducer.js:
const reducer = (state, action) => {
const { todos } = state;
switch (action.type) {
case actionTypes.addTodo:
return {
...state,
todos: [...state.todos, { id: action.payload.id, todo: action.payload.todo, important: false }],
};
case actionTypes.addImportant:
const importantTodo = todos.find((item) => item.id === action.payload);
console.log(state);
return {
...state,
todos: [...state.todos, { ...todos, important: true }],
importantTodos: [...state.importantTodos, { id: importantTodo.id, todo: importantTodo.todo }],
};
default:
throw new Error(`No Matching "${action.type}" - action type`);
}};
When adding ToDo to importantTodos, I'd also like to change it's attribute important:false to important: true in todos array. Currently, this code works without changing the attribute when
todos: [...state.todos, { ...todos, important: true }],
line is deleted. With it it just copies all todos, and stores them as new array of objects at the todos array. I think the problem is in my spread operators as I don't understeand them as I tought I do.
Add this snippet in the addImportant case
const updatedTodos = todos.map(todoEl => {
if(todoEl.id === action.payload){
const {id, todo} = todoEl;
return {id, todo, important: true}
}
return todoEl;
})
Update return statement:
return {
...state,
todos: updatedTodos,
importantTodos: [...state.importantTodos, { id: importantTodo.id, todo: importantTodo.todo }],
};

React - update state array

Context
Hi,
I'm creating a form to create virtual machine. Informations are gathered across multiple pages (components) and centralized in top level component.
It's state object looks like this :
const [vmProp, setVmProp] = useState({
name: "",
image_id: "",
image_name: "",
volumesList: [],
RAM: "",
vcpu: "",
autostart: true,
});
Problem
I want to be able to add/remove a volume to the volumes List and I want volumesList to looks like this :
[
{
name: "main",
size: 1024
},
{
name: "backup",
size: 2048
},
{
name: "export",
size: 2048
}
]
What I've tried
For now I've only tried to add a volume.
1 : working but does not produce what I want
const handleAddVolume = (obj) => {
setVmProp({ ...vmProp,
volumesList: {
...vmProp.volumesList,
[obj.name]: {
size: obj.size,
},
} });
};
It's working but the output is :
[
name: {
size: 1024
}
]
2 : should be working but it's not
const handleAddVolume = (obj) => {
setVmProp({ ...vmProp,
volumesList: {
...vmProp.volumesList,
{
name: obj.name,
size: obj.size,
},
} });
};
output :
[
name: "main",
size: 1024
]
Do you have any ideas on how to handle such state object ?
Thanks
You'll have a better time if you don't need to nest/unnest the volumes list from the other state. (Even more idiomatic would be to have a state atom for each of these values, but for simple values such as booleans and strings, this will do.)
const [vmProps, setVmProps] = useState({
name: "",
image_id: "",
image_name: "",
RAM: "",
vcpu: "",
autostart: true,
});
const [volumesList, setVolumesList] = useState([]);
volumesList shouldn't be object, make it as an array inside handleAddVolume function.
Try the below approach,
const handleAddVolume = (obj) => {
setVmProp({ ...vmProp,
volumesList: [
...vmProp.volumesList,
{
name: obj.name,
size: obj.size,
}
] });
};
Here is a working example:
const Example = (props) => {
const inputRef = createRef();
const [vmProp, setVmProp] = useState({
name: "",
image_id: "",
image_name: "",
volumesList: [],
RAM: "",
vcpu: "",
autostart: true,
});
const { volumesList } = vmProp;
const handleAddVolume = (e) => {
e.preventDefault();
const input = inputRef.current.value;
setVmProp((prevVmProp) => {
const newVmProp = { ...prevVmProp };
newVmProp.volumesList.push({
name: input,
size: 1024,
});
return newVmProp;
});
// reset the input
inputRef.current.value = "";
};
return (
<>
<form>
<input ref={inputRef} type="text" />
<button onClick={handleAddVolume}>Add volume</button>
</form>
{volumesList.map((volume) => (
<div key={volume.name}>{`${volume.name} - ${volume.size}`}</div>
))}
</>
);
};
export default Example;
it's just a proof of concept. Basically, setVmProp accepts a function that gets the up-to-date state value as the update is asynchornus and returns the new value of the state. so using ES6's destructuring function, I make a copy of the latest value of vmProp called newVmProp , then push a new object to newVmProp.volumesList then return newVmProp that contains the newly added volume + everything else. The value of the name I get from an input field. Again this is just a proof of concept.
As I needed to be able to add / remove / replace an object in my array I decided to create it's own state as following :
const [volumesList, setVolumesList] = useState([]);
const handleAddVolume = (obj) => {
setVolumesList((oldList) => [...oldList, obj]);
};
const handleRemoveVolume = (obj) => {
setVolumesList((oldList) => oldList.filter((item) => item.name !== obj.name));
};
const handleEditVolume = (obj) => {
setVolumesList(
volumesList.map((volume) =>
(volume.name === obj.name
? { ...volume, ...obj }
: volume),
),
);
};
Thanks for all your answers !

useEffect hook called on initial render without dependency changing

Okay, I am experiencing some behaviour I don't really understand.
I have this useState hook
const [permanent, setPermanent] = useState(false)
and this useEffect hook
useEffect(() => {
if (permanent) {
dispatch({ value: 'Permanent booth', key: 'period' })
} else {
dispatch({ value: '0', key: 'period' })
}
}, [permanent])
It triggers a rerender on initial render, and I do not call setPermanent upon rendering my component, I have checked this both by commenting every single setPermanent call out in my application. And I have also tried replacing it with a function that logs to the console.
//const [permanent, setPermanent] = useState(false)
const permanent = false
const setPermanent = () => {
console.log('I am called') //does not get called on initial render
}
I know it triggers a rerender because when I comment one of the second dispatch call in it out, it does not trigger the rerender.
useEffect(() => {
if (permanent) {
dispatch({ value: 'Permanent booth', key: 'period' })
} else {
//dispatch({ value: '0', key: 'period' })
}
}, [permanent])
Is there a reason for this, because I cannot seem to find documentation explaining this behaviour?
EDIT --------------
const shopOptions = (() => {
const options = [
{ label: 'Choose a shop', value: '0' },
]
Object.keys(stores).forEach(store => {
options[options.length] = { label: store, value: options.length }
})
return options
})()
const genderOptions = [
{ label: 'Choose a gender', value: '0' },
{ label: 'Female', value: '1' },
{ label: 'Male', value: '2' }
]
const periodOptions = [
{ label: 'Choose a period', value: '0' },
{ label: '1 week', value: '1' },
{ label: '2 weeks', value: '2' },
{ label: '3 weeks', value: '3' },
{ label: '4 weeks', value: '4' }
]
const initialState = {
shop: shopOptions[0],
gender: genderOptions[0],
period: periodOptions[0],
}
function reducer(prevState, { value, key }) {
const updatedElement = { ...prevState[key] }
updatedElement.value = value
return { ...prevState, [key]: updatedElement }
}
//form
const [state, dispatch] = useReducer(reducer, initialState)
useEffect hooks run both after the first render and after every update of variables passed to the dependency array (in your case [permanent]).
Because you have a boolean value that triggers the effect, it's hard to know whether it's the first render or a re-render within the effect. In your case I would consider not using a useEffect here, and instead dispatching what you need while updating the state. For example:
const [permanent, setPermanent] = useState(false)
const makePermanent = () => {
setPermanent(true)
dispatch({ value: 'Permanent booth', key: 'period' })
}
const makeTemporary = () => {
setPermanent(false)
dispatch({ value: '0', key: 'period' })
}
This is my solution. Just a boolean property and ordering hook will do the job.
const _isMounted = React.useRef(false)
const [filter, setFilter] = React.useState('')
React.useEffect(() => {
if (_isMounted.current) {
getData(filter) // Now it will not get called very first time
}
}, [filter])
/* Order is important. [] or so called componentDidMount() will be the last */
React.useEffect(() => {
_isMounted.current = true
return () => {
_isMounted.current = false
}
}, [])

remove full object from Redux initial state when there is no values in the corresponding items

In my reducer, I have the initial state which looks like this:
const initialState = {
isLoading: false,
events: [
{
year: 2021,
place: [
{
id: 1,
name: "BD"
},
{
id: 2,
name: "BD Test"
}
]
},
{ year: 2020, place: [{ id: 3, name: "AMS" }, { id: 4, name: "AMS TEST" }] }
]
};
I have been trying to implement the functionality of deletion operation. So, when the button will be clicked the "deleteItems" action will be dispatched that will remove the corresponding items from the place. This functionality works fine. But,I am trying to remove the whole items from the events array if there is no values in place.
This is what I have tried already but it just removes the individual place. But, I need to write the logic here of removing the whole items when place becomes empty.
case "deleteItems":
return {
...state,
events: state.events.map(event => {
const place = event.place.find(x => x.id === action.id);
if (place) {
return {
...event,
place: event.place.filter(x => x.id !== action.id)
};
}
return event;
})
};
So, after modifications, the state would look like this:(when there is no values in place for year 2021)
const initialState = {
isLoading: false,
events: [
{ year: 2020, place: [{ id: 3, name: "AMS" }, { id: 4, name: "AMS TEST" }] }
]
};
Does anybody know how to accomplish this. Any helps would be highly appreciated.Thanks in Advance.
Demo can be seen from here
I removed the places first.
Then I filtered events based on whether the place array is empty or not.
After that, I returned the state.
case "deleteItems":
const eventsPostDeletingPlaces = state.events.map(event => {
const place = event.place.find(x => x.id === action.id);
if (place) {
return {
...event,
place: event.place.filter(x => x.id !== action.id)
};
}
return event;
});
const eventsWithPlaces = eventsPostDeletingPlaces.filter((each) => each.place.length);
return {
...state,
events: eventsWithPlaces
}
Check the edited sandbox here
Basically the same logic as in the first answer, but with reduce instead of a map and an extra filter. Just an option.
case "deleteItems":
return {
...state,
events: state.events.reduce((events, event) => {
const place = event.place.find(x => x.id === action.id);
if (place) {
event.place = event.place.filter(x => x.id !== action.id);
}
if (event.place.length > 0) {
events.push(event);
}
return events;
}, [])
};
codesandbox

How to add a new item into array in an object that's is in the array?

Here is my state
const initState = [
{
id: 1,
criteria: [],
isInclusion: true,
},
{
id: 2,
criteria: [],
isInclusion: true,
},
];
I am trying to add a new object into criteria array with my dispatch
dispatch(
addCriteria({
id: item.id,
type: item.type,
groupId: 1,
})
);
in the reducer I do the following but it doesnt add to an array of an existing group but instead, it adds as a new object to the array with that criteria added in it.
const addReducer = (state = initState, action) => {
switch (action.type) {
case QUERYGROUPS.ADD_CRITERIA: {
const newCriteria = {
id: action.payload.id,
type: action.payload.type,
};
const newState = [
...state,
state.map(group =>
group.id === action.payload.groupId
? {
...group,
criteria: newCriteria,
}
: group
),
];
return newState;
}
}
};
You are adding all items to the state object (also the one you want to modify) with ...state and than you map over it again. This will not work.
You should change your state object to be an object to access the items by reference and not index and use the id as access. This will also be faster(thanks #Yash Joshi ):
const initState = {
1: {
criteria: [],
isInclusion: true,
},
2: {
criteria: [],
isInclusion: true,
},
};
This will let you access and update the state more easily and easier to stay immutable.
This will let you update it like this:
case QUERYGROUPS.ADD_CRITERIA: {
const newCriteria = {
id: action.payload.id,
type: action.payload.type,
};
const newState = {
...state,
[action.payload.groupId]: {
...state[action.payload.groupId],
criteria: [
...state[action.payload.groupId].criteria,
newCriteria
],
}
};
return newState;
To add a new item to it:
const newState = {
...state,
[action.payload.groupId]: {
isInclusion: false,
criteria: [ ],
}
};
Hope this helps. Happy coding.
Try spread operator (es6):
return [
...state,
newCriteria,
]
This will return a new array with the newCriteria object on it.
Here is how I'd do it:
const newCriteria = {
id: action.payload.id,
type: action.payload.type,
};
const newState = state.map(gr => {
if (gr.id !== action.payload.groupId) {
return gr;
}
return {
...gr,
criteria: [...gr.criteria, newCriteria];
}
});
I think you should follow Domino987 approach it will be faster. But if you still wish to continue with your approach. You can try this:
const newState = state.map(item => item.id === newItem.id ? ({ ...item, ...newItem }) : item );
return newState;
Hope this Helps!

Categories

Resources