In my React state, I want to reorder an array of 3 objects by always putting the selected one in the middle while keeping the others in ascending order.
Right now, I'm using an order property in each object to keep track of the order, but this might not be the best approach.
For example :
this.state = {
selected: 'item1',
items: [
{
id: 'item1',
order: 2
},
{
id: 'item2'
order: 1
},
{
id: 'item3'
order: 3
}
]
}
Resulting array : [item2, item1, item3]
Now, let's imagine that a user selects item2. I will update the selected state property accordingly, but how can I update the items property to end up with a result like this:
this.state = {
selected: 'item2',
items: [
{
id: 'item1',
order: 1
},
{
id: 'item2'
order: 2
},
{
id: 'item3'
order: 3
}
]
}
Resulting array : [item1, item2, item3]
How would you do it? I have seen some lodash utility functions that could help but I would like to accomplish this in vanilla JavaScript.
You could do something crude like this:
// Create a local shallow copy of the state
var items = this.state.items.slice()
// Find the index of the selected item within the current items array.
var selectedItemName = this.state.selected;
function isSelectedItem(element, index, array) {
return element.id === selectedItemName;
};
var selectedIdx = items.findIndex(isSelectedItem);
// Extract that item
var selectedItem = items[selectedIdx];
// Delete the item from the items array
items.splice(selectedIdx, 1);
// Sort the items that are left over
items.sort(function(a, b) {
return a.id < b.id ? -1 : 1;
});
// Insert the selected item back into the array
items.splice(1, 0, selectedItem);
// Set the state to the new array
this.setState({items: items});
This assumes the size of the items array is always 3!
I'm gonna be lazy and just outline the steps you need to take.
Pop the selected item out of the starting array
Push the first item of the starting array into a new array
Push the selected item into the new array
Push the last item of the starting array into the new array
Set your state to use the new array
You can do something like:
NOTE: This works assuming there would three items in the array. However, if there are more we just need to specify the index position in the insert function.
this.state = {
selected: 'item1',
items: [
{
id: 'item1',
order: 1
},
{
id: 'item2',
order: 2
},
{
id: 'item3',
order: 3
}
]
};
// To avoid mutation.
const insert = (list, index, newListItem) => [
...list.slice(0, index), // part of array before index arg
newListItem,
...list.slice(index) // part of array after index arg
];
// Get selected item object.
const selectedValue = value => this.state.items.reduce((res, val) => {
if (val.id === selectedValue) {
res = val;
}
return res;
}, {});
const filtered = this.state.items.filter(i => i.id !== state.selected);
const result = insert(filtered, 1, selectedValue(this.state.selected));
We can get rid of the extra reduce if instead of storing id against selected you store either the index of the item or the whole object.
Of course we need to use this.setState({ items: result }). This solution would also ensure we are not mutating the original state array at any point.
I put together a fully working example what can be extended on so you can experiment with different ways to achieve your intended use-case.
In this case I created a button component and rendered three of them to provide a means of changing the selected state.
Important things to remember, always use the setState() function for updating React Class state. Also, always work on state arrays and objects with a cloned variable as you'll want to update the whole object/array at once. Don't modify attributes of pointer variables pointing to state objects or arrays.
It is very possible to add bugs to your code by referencing state objects/arrays and then changing their properties (accidentally or not) by modifying the pointer referencing the object. You will lose all guarantees on how the state will update, and comparing prevState or nextState with this.state may not work as intended.
/**
* #desc Sub-component that renders a button
* #returns {HTML} Button
*/
class ChangeStateButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = ({
//any needed state here
});
}
handleClick(e) {
//calls parent method with the clicked button element and click state
this.props.click(e.nativeEvent.toElement.id);
}
render() {
return (
<button
id = {this.props.id}
name = {this.props.name}
className = {this.props.className}
onClick = {this.handleClick} >
Reorder to {this.props.id}!
</button>
);
}
}
/**
* #desc Creates button components to control items order in state
* #returns {HTML} Bound buttons
*/
class ReorderArrayExample extends React.Component {
constructor(props) {
super(props);
this.reorderItems = this.reorderItems.bind(this);
this.state = ({
selected: 'item1',
//added to give option of where selected will insert
selectedIndexChoice: 1,
items: [
{
id: 'item1',
order: 2
},
{
id: 'item2',
order: 1
},
{
id: 'item3',
order: 3
}
]
});
}
reorderItems(selected) {
const {items, selectedIndexChoice} = this.state,
selectedObjectIndex = items.findIndex(el => el.id === selected);
let orderedItems = items.filter(el => el.id !== selected);
//You could make a faster reorder algo. This shows a working method.
orderedItems.sort((a,b) => { return a.order - b.order })
.splice(selectedIndexChoice, 0, items[selectedObjectIndex]);
//always update state with setState function.
this.setState({ selected, items: orderedItems });
//logging results to show that this is working
console.log('selected: ', selected);
console.log('Ordered Items: ', JSON.stringify(orderedItems));
}
render() {
//buttons added to show functionality
return (
<div>
<ChangeStateButton
id='item1'
name='state-button-1'
className='state-button'
click={this.reorderItems} />
<ChangeStateButton
id='item2'
name='state-button-2'
className='state-button'
click={this.reorderItems} />
<ChangeStateButton
id='item3'
name='state-button-2'
className='state-button'
click={this.reorderItems} />
</div>
);
}
}
/**
* #desc React Class renders full page. Would have more components in a real app.
* #returns {HTML} full app
*/
class App extends React.Component {
render() {
return (
<div className='pg'>
<ReorderArrayExample />
</div>
);
}
}
/**
* Render App to DOM
*/
/**
* #desc ReactDOM renders app to HTML root node
* #returns {DOM} full page
*/
ReactDOM.render(
<App/>, document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
<!-- This div's content will be managed by React. -->
</div>
Related
I want to remove an object from my List array based on its properties value.
Right now I am using findIndex to see if there is an index ID matching my event.target.id.
This is an example of one of the objects in my list array:
{artist: "artist name",
genre: "RnB",
id: 1,
rating: 0,
title: "song name"}
This is my code:
console.log(e.target.id);
const list = this.state.playlist;
list.splice(
list.findIndex(function(i) {
return i.id === e.target.id;
}),
1
);
console.log(list);
}
how ever, instead of it removing the clicked item from the array, it removes the last item, always.
When I do this:
const foundIndex = list.findIndex((i) => i.id === e.target.id)
console.log(foundIndex)
I get -1 back.
What's the problem here?
Use filter for this. Use it to filter out the objects from state where the id of the button doesn't match the id of the current object you're iterating over. filter will create a new array you can then update your state with rather than mutating the existing state (which is bad) which is what is currently happening.
Assuming you're using React here's a working example.
const { Component } = React;
class Example extends Component {
constructor() {
super();
this.state = {
playlist: [
{id: 1, artist: 'Billy Joel'},
{id: 2, artist: 'Madonna'},
{id: 3, artist: 'Miley Cyrus'},
{id: 4, artist: 'Genesis'},
{id: 5, artist: 'Jethro Tull'}
]
};
}
// Get the id from the button (which will be
// a string so coerce it to a number),
// and if it matches the object id
// don't filter it into the new array
// And then update the state with the new filtered array
removeItem = (e) => {
const { playlist } = this.state;
const { id } = e.target.dataset;
const updated = playlist.filter(obj => {
return obj.id !== Number(id);
});
this.setState({ playlist: updated });
}
render() {
const { playlist } = this.state;
return (
<div>
{playlist.map(obj => {
return (
<div>{obj.artist}
<button
data-id={obj.id}
onClick={this.removeItem}
>Remove
</button>
</div>
);
})}
</div>
);
}
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
I have a following array,
const bio = [
{id: 1, name: "Talha", age: 26},
{id: 2, name: "Ayub", age: 22}
]
Here is a complete code of mine,
import './App.css';
import React, {useState} from 'react';
const bio = [
{id: 1, name: "Talha", age: 26},
{id: 2, name: "Ayub", age: 22}
]
const App = () => {
const [bioData, setbioData] = useState(bio);
const clear_function = () => setbioData([])
return (
<div className="App">
{
bioData.map((arr) =>
<>
<h3 key={arr.id}>Name: {arr.name}, Age: {arr.age}</h3>
<button onClick={() => clear_function()}>Click me</button>
</>
)}
</div>
);
}
export default App;
Now, this code hooks the whole array to useState. Whenever I click the button "Click me", it sets the state to empty array and returns empty array as a result.
But what if I want to remove a specific row of the array? I have made two buttons, each for one row. What I want to do is if I click the first button, it removes the first row from the array as well and keeps the 2nd array.
Similarly, if I want to change a specific attribute value of a specific row, how can I do that using useState hook? For example, I want to change the name attribute of the 2nd row. How is it possible to do this with useState?
And same case for addition. IF I make a form and try to add a new row into my bio array, how would I do that? I searched it up on Google, found a similar post as well but the answer given in it wasn't satisfactory and did not work, which is why I am asking this question again.
If I understood the question right, I think you can pass the updated object to set state and that'll be it.
To change a particular object in array, do something lie this:
// Update bio data with id = 2
setbioData(prevValue =>
[...prevValue].map(el =>
el.id === 2 ? ({...el, name:'new name'}) : el)
)
Also, you have set key at the wrong place
Full refactored code:
const bio = [
{id: 1, name: "Talha", age: 26},
{id: 2, name: "Ayub", age: 22}
]
const App = () => {
const [bioData, setbioData] = useState(bio);
const clear_function = (id) => {
setbioData(prevValue =>
[...prevValue].map(el =>
el.id === id ? ({...el, name:'new name'}) : el)
)
}
return (
<div className="App">
{
bioData.map((arr) =>
<div key={arr.id}>
<h3>Name: {arr.name}, Age: {arr.age}</h3>
<button onClick={() => clear_function(arr.id)}>Click me</button>
</div>
)}
</div>
);
}
Adding a row to the array with react useState would be as simple as the following:
function addRow(objToAdd){
//get old data and add new row
let newBioData = bioData.push(objToAdd)
setBioData(newBioData)
}
To remove a specific row you would need to find the object within the bioData array, remove it and set the new bioData like so:
function removeRow(rowId){
//Filter the array by returning every object with a different Id than the one you want to remove
let newBioData = bioData.filter(function (value, index, arr){ return value.id != rowId })
setBioData(newBioData)
}
To update the state you could use the spread operator like so:
function updateRow(rowId, data){
//Iterate list and update certain row
bioData.filter(function (value, index, arr){
//Row to update
if(value.id == rowId){
return {name: data.name, age: data.age}
}else{
//Nothing to update, return current item (spread all values)
return {...value}
}
})
setBioData ([])
}
I'm not sure if I fully understand your question, but when you want to change the state in a functional component, you can't directly change the state object, instead you need to create a new desired state object, and then set the state to that object.
for example, if you want to add a new row to your array, you'll do the following:
setbioData((currBioData) => [...oldBioData, {id: 3, name: "Bla", age: 23}]);
When you want to change the state based on the current state, there's an option to send the setState function a callback function which accepts the current state, and then using the spread operator we add a new row to the array.
I'm not going to get into why it is better to pass setState a function to modify current state but you can read about it in React official docs
Looks like there are 3 questions here. I'll do my best to help.
"what if I want to remove a specific row of the array?"
One way is to filter your current array and update the state with the new array.
In your example: onClick={()=>setbioData(arr.filter(row=>row.id !== arr.id))}
"if I want to change a specific attribute value of a specific row, how can I do that using useState hook?"
You will need to create a new array with the correct information and save that array to state.
In your example: [... bioData, {id:/row_id/,name:/new name/,age:/new age/}]
"IF I make a form and try to add a new row into my bio array, how would I do that"
In this case, you would push a new object into your array. In your example:
setbioData(previousData=>previousData.push({id:previousData.length+1,name:/new name/,age:/new age/})
I hope this helps you, best of luck
import './App.css';
import React, {useState} from 'react';
const bio = [
{id: 1, name: "Talha", age: 26},
{id: 2, name: "Ayub", age: 22}
]
const App = () => {
const [bioData, setbioData] = useState(bio);
const clear_function = (i) => {
let temp = bioData.slice()
temp = temp.splice(i, 1)
setbioData(temp)
}
return (
<div className="App">
{
bioData.map((arr, i) =>
<>
<h3 key={arr.id}>Name: {arr.name}, Age: {arr.age}</h3>
<button onClick={() => clear_function(i)}>remove row</button>
</>
)}
</div>
);
}
export default App;
Same way you need to just to update a specific attribute just update that element in the temp array and do setBioData(temp)
Similarly, If you want to add another row do temp.push({id: 1, name: "Talha", age: 26}) and do setBioData(temp)
So I have an e-commerce webpage but for some reason, after adding an item past the first time to a cart it starts to double the value of units in cart as well as double my Toasts. I am wondering what I am doing wrong here. My initial State is 0 for cartItem. Any help will be much appreciated.
here is what I am working with:
Example of cartItem Object:
[{
description: "...."
featured: false
id: "6u7pLcaGApuGtiNAf6zLMf"
image: ["//images.ctfassets.net/f1r553pes4gs/17rq7BQ76Q7ouq…010636019e9b3cbc3a10/il_794xN.2378509691_kaep.jpg"]
inCart: false
ingredients: (2) ["Distilled Water", "99.99% Fine Silver Rods"]
price: 20
productName: "Quintessence Colloidal Silver (4 fl oz)"
slug: "quintessence-colloidal-silver-4oz"
units: 9
}]
Shorted Version of Code:
export class StoreProvider extends Component {
//Initialized State ready for API Data
state = {
products: [],
featuredProducts: [],
sortedProducts: [],
price: 0,
maxPrice: 0,
minPrice: 0,
units: 0,
loading: true,
//FIXME CART
cartItem: []
}
handleAddToCart = (e, products) => {
this.setState(state => {
const cartItem = state.cartItem;
let productsAlreadyInCart = false;
cartItem.forEach(cp => {
if (cp.id === products.id) {
//Have tried ++
cp.units+= 1;
productsAlreadyInCart = true;
this.successfullCartToast()
}
});
if (!productsAlreadyInCart) {
cartItem.push({ ...products});
}
localStorage.setItem('cartItem', JSON.stringify(cartItem));
return { cartItem: cartItem };
});
}
}
//Button is in seperate component
<button
className="btn-primary rounded col-sm-6 col-lg-12 align-self-center ml-1 p-2"
onClick={(e) => handleAddToCart(e, product)}>
+ Cart
</button>
Issue
You are mutating existing state and toasting every cart item you check.
Solution
First search the cart array if item is already contained. If it is already contained then simply map the cart and update the appropriate index, otherwise, append to a shallowly copied cart item array.
Also, setState should be a pure function, so don't do side-effects like setting localStorage inside the setState functional update, instead use the setState callback, or preferably, the componentDidUpdate lifecycle function. Or you can just set localStorage with the same value you're updating state with.
handleAddToCart = (e, products) => {
const itemFoundIndex = this.state.cartItem.findIndex(
cp => cp.id === products.id
);
let cartItem;
if (itemFoundIndex !== -1) {
this.successfullCartToast();
// map cart item array and update item at found index
cartItem = this.state.cartItem.map((item, i) =>
i === itemFoundIndex ? { ...item, units: item.units + 1 } : item
);
} else {
// shallow copy into new array, append new item
cartItem = [...this.state.cartItem, products];
}
localStorage.setItem("cartItem", JSON.stringify(cartItem));
this.setState({ cartItem });
};
So, cartItem is an Object, looking something like:
[{'id': 123, 'units': 2}, {'id': 345, 'units': 1}, ...] ?
One thing to try would be to make a deep copy of the Object, so it doesn't changes while updating:
handleAddToCart = (e, products) => {
this.setState(state => {
//const cartItem = state.cartItem;
// make deep copy, so state doesn't change while manipulating:
const cartItem = JSON.parse(JSON.stringify( state.cartItem ));
let productsAlreadyInCart = false;
cartItem.forEach(cp => {
if (cp.id === products.id) {
//Have tried ++
cp.units += 1;
productsAlreadyInCart = true;
this.successfullCartToast()
}
});
if (!productsAlreadyInCart) {
cartItem.push({ ...products});
}
localStorage.setItem('cartItem', JSON.stringify(cartItem));
return { cartItem: cartItem };
});
}
}
I'm having trouble updating a list of elements using React, when I run the code below and click on a 'star' element, react updates ALL the elements in this.state.stars instead of just the element at the given index:
class Ratings extends React.Component {
constructor(props) {
super(props);
let starArr = new Array(parseInt(this.props.numStars, 10)).fill({
icon: "*",
selected: false
});
this.state = {
stars: starArr
};
this.selectStar = this.selectStar.bind(this);
}
selectStar(ind) {
this.setState({
stars: this.state.stars.map((star, index) => {
if (index === ind) star.selected = !star.selected;
return star;
})
});
}
makeStars() {
return this.state.stars.map((star, ind) => (
<span
className={star.selected ? "star selected" : "star"}
onClick={() => this.selectStar(ind)}
key={ind}
>
{star.icon}
</span>
));
}
render() {
return (
<div className="star-container">
<span>{this.makeStars()}</span>
</div>
);
}
}
Can anyone point me in the right direction here? Not sure why this is happening!
Your problem is in how you're instantiating your Array:
let starArr = new Array(parseInt(this.props.numStars, 10)).fill({
icon: "*",
selected: false
});
What that line is doing is filling each item in the array with the same object. Not objects all with the same values, but a reference to the same object. Then, since you're mutating that object in your click handler, each item in the Array changes because they're all a reference to that same object.
It's better to do a non-mutating update, like this:
this.setState({
stars: this.state.stars.map((star, index) =>
(index === ind)
? { ...star, selected: !star.selected }
: star
)
});
This will instead create a copy of the object at the Array index except with the selected property toggled.
How to not lose React state in this case when I do filter?
When I do filter I lose my previous state and program work not correct, for example, if I choose category sport, then try category fashion, I can't see anything in fashion, the case this all was dropped, when I choose sport.
I am new in React I would like to hear the best practices.
FilterCategory(e) {
// Filter
const filter = this.state.items.filter(
(item) => {
return item.category.indexOf(e.target.name) !== -1
}
)
// Update state
this.setState({
items:filter
})
}
Why not use query string to store filters.
Suppose your url is /products and filter selected is say gender male. then you can append
/products?gender=male.
Now in react using libraries like react-router you can access this query params and get the current filter selected and then perform whatever options you want to like call api etc.
If you further select other filters then just append the new filters again to query params like field1=value1&field2=value2&field3=value3...
And again as location props of react will change you will get the new params in the component.
Advantages of this technique.
1) No headache of maintaining state.
Storing filters in state can become complex and clumsy if not done in proper way.
2) No problem if page gets refreshed.
Suppose your user have selected filters and, page gets refreshed, all filters will be lost if saved in state. But if query string is done it will remain intact.
Due to this reasons i think query string is better option then state.
Just store filtered values as another state property.
state = {
items: [],
filteredItems: []
}
When you do filtering always refer to items and override filteredItems
filterItems(e) {
const filtered = this.state.items.filter(
(item) => {
return item.category.indexOf(e.target.name) !== -1
}
)
this.setState({filteredItems: filtered});
}
The problem is you're setting items to the filtered array returned by filter.
You could use another proprety in your state to store the target's item, so you're keeping your items as they are, something like this:
this.state({
items: [...yourItems],
chosenItem: []
})
filterCategory(e) {
let filter = this.state.items.filter((item) => {
item.category.indexOf(e.target.name) !== -1
})
// Update state keeping items intact
this.setState({
chosenItem: filter
})
}
You can just store and update the filter query in state and only return the filtered items in the render function instead of updating state.
class App extends React.Component {
state = {
items: [
{ category: ['fashion'], name: 'Gigi Hadid', id: 1 },
{ category: ['sports'], name: 'Lebron James', id: 2 },
{ category: ['fashion', 'sports'], name: 'Michael Jordan', id: 3 },
{ category: ['sports', 'tech'], name: 'Andre Iguodala', id: 4 },
{ category: ['tech'], name: 'Mark Zuckerberg', id: 5 },
],
filter: '',
}
handleChange = (e) => {
this.setState({ filter: e.target.value });
}
render() {
const { items, filter } = this.state;
let shownItems = items;
if (filter) {
shownItems = items.filter(({ category }) => category.includes(filter));
}
return (
<div>
<select value={filter} onChange={this.handleChange}>
<option value="">All</option>
<option value="fashion">Fashion</option>
<option value="sports">Sports</option>
<option value="tech">Tech</option>
</select>
<div>
<ul>
{shownItems.map(({ name, id }) => <li key={id}>{ name }</li>)}
</ul>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>