filtering array to remove item react - javascript

I'm trying to use filter to remove an object from the array. When I click on the recently added item it will console.log the items id but doesn't remove the item from the array, not sure where I'm going wrong?
import React, { Component } from 'react'
import { reduxForm } from 'redux-form'
// import Input from '../forms/Input/Input'
import actions from './actions'
import { connect } from 'react-redux'
import styles from './Catalogue.styl'
// import Checklist from './Checklist/Checklist'
#reduxForm({
form: 'orderReview',
})
#connect(null, actions)
export default class Catalogue extends Component {
constructor() {
super()
this.state = {
filterText: '',
favourites: [],
data: [
{ id: 1, label: 'baguettes' },
{ id: 2, label: 'bread' },
{ id: 3, label: 'potatoes' },
{ id: 4, label: 'rice' },
{ id: 5, label: 'pasta' },
{ id: 6, label: 'chicken' },
{ id: 7, label: 'beans' },
{ id: 8, label: 'apples' },
{ id: 9, label: 'oranges' },
{ id: 10, label: 'grapes' },
{ id: 11, label: 'biscuits' },
],
}
}
handleFilterUpdate = event => {
this.setState({
filterText: event.target.value,
})
}
addFavourite = (id) => {
const favList = this.state.favourites.concat([id])
this.setState({
favourites: favList,
})
console.log(id)
}
removeFavourite = (id) => {
console.log(id)
const removeFav = this.state.favourites.filter((_, i) => i !== id)
this.setState({
favourites: removeFav,
})
}
render() {
const {
data,
filterText,
favourites,
} = this.state
const NamesList = props => (
<div>
{props.data.filter(items => {
return items.label.toLowerCase().indexOf(filterText.toLowerCase()) >= 0
})
.map(item => {
return (
<div
key={item.id}
onClick={() => props.addFavourite(item.id)}
>
{item.label}
</div>
)
}
)
}
</div>
)
const SaveName = props => {
const idList = props.favourites.map(id => {
const { label } = data[id]
return (
<div>
<br />
<li key={id} onClick={() => props.removeFavourite(data[id])}>{label}</li>
</div>
)
})
return (
<div>{idList}</div>
)
}
return (
<div>
<div className={styles.filtersList}>
<ul className={styles.filtersUl}>
<li className={styles.filtersLi}>znacky</li>
<li className={styles.filtersLi}>zeme</li>
<li className={styles.filtersLi}>Specialni</li>
</ul>
</div>
<input
type="text"
value={filterText}
onChange={this.handleFilterUpdate}
placeholder="Hledat podle nazvu"
/>
<NamesList data={data} addFavourite={this.addFavourite}/>
{filterText}
<SaveName favourites={favourites} removeFavourite={this.removeFavourite} />
</div>
)
}
}

You are iterating through your entire array, and you compare the parameter id with the index of the currently processed item of the array.
Instead, compare the item.id with the parameter, not with i:
class MyApp extends React.Component {
constructor() {
super()
this.state = {
favourites: [
{ id: 1, label: 'baguettes' },
{ id: 2, label: 'bread' },
{ id: 3, label: 'potatoes' },
{ id: 4, label: 'rice' },
{ id: 5, label: 'pasta' },
{ id: 6, label: 'chicken' },
{ id: 7, label: 'beans' },
{ id: 8, label: 'apples' },
{ id: 9, label: 'oranges' },
{ id: 10, label: 'grapes' },
{ id: 11, label: 'biscuits' },
],
}
}
removeFavourite = (id) => {
const removeFav = this.state.favourites.slice();
removeFav.splice(id, 1);
this.setState({
favourites: removeFav
})
}
render() {
return(
<ul>
{this.state.favourites.map((item, i) => <li key={item.id}>{item.label} <button onClick={this.removeFavourite.bind(this, i)}>Remove</button></li>)}
</ul>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("myApp"));
<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="myApp"></div>
Alternatively, you could also just use splice() to remove the item directly:
class MyApp extends React.Component {
constructor() {
super()
this.state = {
favourites: [
{ id: 1, label: 'baguettes' },
{ id: 2, label: 'bread' },
{ id: 3, label: 'potatoes' },
{ id: 4, label: 'rice' },
{ id: 5, label: 'pasta' },
{ id: 6, label: 'chicken' },
{ id: 7, label: 'beans' },
{ id: 8, label: 'apples' },
{ id: 9, label: 'oranges' },
{ id: 10, label: 'grapes' },
{ id: 11, label: 'biscuits' },
],
}
}
removeFavourite = (id) => {
const removeFav = this.state.favourites.filter(item => item.id-1 != id)
this.setState({
favourites: removeFav
})
}
render() {
return(
<ul>
{this.state.favourites.map((item, i) => <li key={item.id}>{item.label} <button onClick={this.removeFavourite.bind(this, i)}>Remove</button></li>)}
</ul>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("myApp"));
<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="myApp"></div>

Related

getting sum of previous element from list VUEJS

I am trying to get sum of previous element and add this to the existing list.
This is my current list:
ongoing: [
{
id: 'id1',
name: 'clientName',
productionTime: 15,
},
{
id: 'id2',
name: 'client',
productionTime: '15'
}
],
this is the result I want to achieve:
ongoing: [
{
id: 'id1',
name: 'clientName',
productionTime: 15,
sumofprevious: 15
},
{
id: 'id2',
name: 'client',
productionTime: 15,
sumofprevious: 30 (note: this comes from 15 + 15)
}
],
I use vuejs 3 with Pinia.
I tried many codes/examples but this is the closest one but it doesn't work as I want it. It doesn't read productionTime from ongoing
const thisList = computed(() => {
let array = storeOrders.ongoing.productionTime,
sum = 0,
newarray = array.map(value => sum += value)
return console.log(newarray)
})
You can use computed property:
const { computed, reactive } = Vue
const app = Vue.createApp({
setup() {
let ongoing = reactive([{id: 'id1', name: 'clientName', productionTime: 15,}, {id: 'id2', name: 'client', productionTime: '15'}])
const res = computed(() => {
let sum = 0
return ongoing.map(o => {
sum += +o.productionTime
return {...o, sumofprevious: sum}
})
})
const add = () => {
ongoing.push({id: Math.floor(Date.now() / 1000), name: 'name', productionTime: Math.ceil(Math.random() * 20),})
}
return { ongoing, res, add };
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
<div id="demo">
<button #click="add">add</button>
<br />
ongoing: {{ ongoing }}
<br /><br />
result: {{ res }}
</div>
I would try to compute this:
const ongoing = [
{
id: 'id1',
name: 'clientName',
productionTime: 15,
sumOfPrevious: 0,
},
{
id: 'id2',
name: 'client',
productionTime: 15,
}
];
const sumOfPrev = () => {
return ongoing.map((el, i) => {
if (i !== 0) {
el.sumOfPrevious = ongoing[i-1].productionTime + el.productionTime;
}
return el;
})
}
console.log(sumOfPrev());

Displaying mapped data without being clicked before showing

I am having a little difficulty with my data. I was able to get all mapped data currently but without me clicking the categories, the data won't be displayed.
Here's an example:
const categoriesData = [
{
name: 'All',
label: 'All',
total: '18',
className: 'activeCategory'
},
{
name: 'Business Services',
label: 'Business_Services',
total: '18'
},
{
name: 'Design Services',
label: 'Design_Services',
total: '18'
},
{
name: 'Education Services',
label: 'Education_Services',
total: '18'
},
{
name: 'Finance Services',
label: 'Finance_Services',
total: '18'
},
{
name: 'IT Services',
label: 'IT_Services',
total: '18'
},
{
name: 'Legal Services',
label: 'Legal_Services',
total: '18'
},
{
name: 'Manufacturing',
label: 'Manufacturing',
total: '18'
},
{
name: 'Marketing',
label: 'Marketing',
total: '18'
}
];
const postsData = {
All: [
{ id: 1, name: 'Post 3' },
{ id: 2, name: 'Post 2' }
],
Business_Services: [
{ id: 1, name: 'Post 3' },
{ id: 2, name: 'Post 2' }
],
Design_Services: [
{ id: 1, name: 'Post 5' },
{ id: 2, name: 'Post 2' }
],
Education_Services: [
{ id: 1, name: 'Post 1' },
{ id: 2, name: 'Post 2' }
],
Finance_Services: [
{ id: 1, name: 'Post 1' },
{ id: 2, name: 'Post 2' }
],
IT_Services: [
{ id: 1, name: 'Post 1' },
{ id: 2, name: 'Post 2' }
],
Legal_Services: [
{ id: 1, name: 'Post 1' },
{ id: 2, name: 'Post 2' }
],
Manufacturing: [
],
Marketing: [
{ id: 1, name: 'Post 1' },
{ id: 2, name: 'Post 27675' }
]
};
function fakePostsApi(catName) {
return new Promise((resolve) =>
setTimeout(() => {
resolve(postsData[catName]);
}, 1000)
);
}
function Main() {
const [categories, setCategories] = React.useState(categoriesData);
const [catName, setCatName] = React.useState();
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
if (catName) {
fakePostsApi(catName)
.then(setPosts);
}
}, [catName]);
return (
<div>
{categories.length > 0 ? (
categories.map((category, i) => {
return (
<button key={i} onClick={() => setCatName(category.label)}>
{category.name}
</button>
);
})
) : (
<p>Loading...</p>
)}
<div>
{posts.length === 0 ? (
<p>No posts...</p>
) : (
posts.map((post) => <div key={post.id}>{post.name}</div>)
)}
</div>
</div>
);
}
ReactDOM.render(
<Main />,
root
)
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<div id="root"></div>
My main problem is: I want the values of all to be displayed first(just like active status) when page loads without being clicking the All button.
Set the default value of catName to be the label of the 0 item of the categories:
const [catName, setCatName] = React.useState(categories[0] && categories[0].label);
Or optional chaining (?.) if supported:
const [catName, setCatName] = React.useState(categories[0]?.label);
const categoriesData = [{"name":"All","label":"All","total":"18","className":"activeCategory"},{"name":"Business Services","label":"Business_Services","total":"18"},{"name":"Design Services","label":"Design_Services","total":"18"},{"name":"Education Services","label":"Education_Services","total":"18"},{"name":"Finance Services","label":"Finance_Services","total":"18"},{"name":"IT Services","label":"IT_Services","total":"18"},{"name":"Legal Services","label":"Legal_Services","total":"18"},{"name":"Manufacturing","label":"Manufacturing","total":"18"},{"name":"Marketing","label":"Marketing","total":"18"}];
const postsData = {"All":[{"id":1,"name":"Post 3"},{"id":2,"name":"Post 2"}],"Business_Services":[{"id":1,"name":"Post 3"},{"id":2,"name":"Post 2"}],"Design_Services":[{"id":1,"name":"Post 5"},{"id":2,"name":"Post 2"}],"Education_Services":[{"id":1,"name":"Post 1"},{"id":2,"name":"Post 2"}],"Finance_Services":[{"id":1,"name":"Post 1"},{"id":2,"name":"Post 2"}],"IT_Services":[{"id":1,"name":"Post 1"},{"id":2,"name":"Post 2"}],"Legal_Services":[{"id":1,"name":"Post 1"},{"id":2,"name":"Post 2"}],"Manufacturing":[],"Marketing":[{"id":1,"name":"Post 1"},{"id":2,"name":"Post 27675"}]};
function Main() {
const [categories, setCategories] = React.useState(categoriesData);
const [catName, setCatName] = React.useState(categories[0] && categories[0].label);
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
if (catName) {
fakePostsApi(catName)
.then(setPosts);
}
}, [catName]);
return (
<div>
{categories.length > 0 ? (
categories.map((category, i) => {
return (
<button key={i} onClick={() => setCatName(category.label)}>
{category.name}
</button>
);
})
) : (
<p>Loading...</p>
)}
<div>
{posts.length === 0 ? (
<p>No posts...</p>
) : (
posts.map((post) => <div key={post.id}>{post.name}</div>)
)}
</div>
</div>
);
}
function fakePostsApi(catName) {
return new Promise((resolve) =>
setTimeout(() => {
resolve(postsData[catName]);
}, 1000)
);
}
ReactDOM.render(
<Main />,
root
)
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<div id="root"></div>

Updating state array of objects from api call

Hy, let me explain my problem, i have a state of tag called tag_data :
const [tagData, setTagData] = useState([
{ key: '1', label: 'Music', active: 0 },
{ key: '2', label: 'Sport', active: 0 },
{ key: '3', label: 'Dance', active: 0 },
{ key: '4', label: 'Cook', active: 0},
{ key: '5', label: 'Video Games', active: 0},
{ key: '6', label: 'Travel', active: 0 },
{ key: '7', label: 'Picture', active: 0 },
{ key: '8', label: 'Animals', active: 0 },
{ key: '9', label: 'Coding', active: 0},
{ key: '10', label: 'Party', active: 0},
])
I do a api call for get ACTIVE tag from my user :
useEffect(() => {
const fetchData = async () => {
setLoad(true)
try {
const result = await axios.post('/user/activetag')
console.log(result.data.active_tag)
setTagData({
// update
})
} catch (error) {
console.log(error)
}
setLoad(false)
}
fetchData()
}, [])
Then the result store the active tags like this :
active_tag: Array(5)
0: {tag_id: 1, label: "Music"}
1: {tag_id: 2, label: "Sport"}
2: {tag_id: 3, label: "Dance"}
3: {tag_id: 4, label: "Cook"}
4: {tag_id: 5, label: "Video Games"}
I would like to update the tagData state and put active to 1 where the tag_id is equal to the key of tagData state, any idea ?
Full code :
import React, {useState, useEffect} from "react";
import { makeStyles } from '#material-ui/core/styles';
import Chip from '#material-ui/core/Chip';
import Paper from '#material-ui/core/Paper';
import DoneIcon from '#material-ui/icons/Done';
import axios from 'axios'
import Loading from '../../../../Loading/Loading'
const useStyles = makeStyles((theme) => ({
// style
})
export default function TagUser(){
const classes = useStyles();
const [load, setLoad] = useState(false)
const [tagData, setTagData] = useState([
{ key: '1', label: 'Music', active: 0 },
{ key: '2', label: 'Sport', active: 0 },
{ key: '3', label: 'Dance', active: 0 },
{ key: '4', label: 'Cook', active: 0},
{ key: '5', label: 'Video Games', active: 0},
{ key: '6', label: 'Travel', active: 0 },
{ key: '7', label: 'Picture', active: 0 },
{ key: '8', label: 'Animals', active: 0 },
{ key: '9', label: 'Coding', active: 0},
{ key: '10', label: 'Party', active: 0},
])
useEffect(() => {
const fetchData = async () => {
setLoad(true)
try {
const result = await axios.post('/user/activetag')
console.log(result.data)
setTagData({
// update
})
} catch (error) {
console.log(error)
}
setLoad(false)
}
fetchData()
}, [])
const handleDelete = (key) => {
//delete
}
const handleSubmit = (key) => {
//submit
}
if(load){
return <Loading/>
} else {
return(
<Paper variant="outlined" square component="span" className={classes.root}>
{
tagData.map((data) => {
if (data.active === 0) {
return (
<li key={data.key}>
<Chip
variant="outlined"
color="secondary"
label={data.label}
className={classes.chip}
onDelete={() => handleSubmit(data.key)}
deleteIcon={<DoneIcon />}
/>
</li>
)
} else {
return (
<li key={data.key}>
<Chip
color="secondary"
label={data.label}
className={classes.chip}
onDelete={() => handleDelete(data.key)}
/>
</li>
)
}
})
}
</Paper>
)
}
}
Disclosure: I am the author of the suspense-service library used in this answer.
If you're open to using a 3rd-party library, it can significantly simplify your data-fetching logic. You won't need a load state, or a useEffect(), the component will only render when the list is ready:
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import Chip from '#material-ui/core/Chip';
import Paper from '#material-ui/core/Paper';
import DoneIcon from '#material-ui/icons/Done';
import axios from 'axios';
import { createService, useService } from 'suspense-service';
import Loading from '../../../../Loading/Loading';
const defaultTags = [
{ key: '1', label: 'Music', active: 0 },
{ key: '2', label: 'Sport', active: 0 },
{ key: '3', label: 'Dance', active: 0 },
{ key: '4', label: 'Cook', active: 0},
{ key: '5', label: 'Video Games', active: 0},
{ key: '6', label: 'Travel', active: 0 },
{ key: '7', label: 'Picture', active: 0 },
{ key: '8', label: 'Animals', active: 0 },
{ key: '9', label: 'Coding', active: 0},
{ key: '10', label: 'Party', active: 0},
];
const UserActiveTags = createService(async (allTags) => {
try {
const result = await axios.post('/user/activetag');
console.log(result.data.active_tag);
const activeTags = result.data.active_tag.map((tag) => tag.tag_id);
const activeTagsSet = new Set(activeTags);
return allTags.map((tag) => ({
...tag,
active: activeTagsSet.has(tag.key) ? 1 : 0
}));
} catch (error) {
console.log(error);
return allTags;
}
});
export default function TagUser() {
return (
<UserActiveTags.Provider request={defaultTags} fallback={<Loading />}>
<TagList />
</UserActiveTags.Provider>
);
}
const useStyles = makeStyles((theme) => ({
// style
}));
function TagList() {
const { root, chip } = useStyles();
const tagData = useService(UserActiveTags);
const handleDelete = (key) => {
//delete
};
const handleSubmit = (key) => {
//submit
};
const tagList = tagData.map(({ active, key, label }) => {
const props = active === 0
? { variant: 'outlined', onDelete: () => handleSubmit(key), deleteIcon: <DoneIcon /> }
: { variant: 'default', onDelete: () => handleDelete(key) };
return (
<li key={key}>
<Chip
color="secondary"
label={label}
className={chip}
{...props}
/>
</li>
);
});
return (
<Paper variant="outlined" square={true} component="span" className={root}>
{tagList}
</Paper>
);
}
If you need tagData to be stateful, then
const tagData = useService(UserActiveTags);
needs to be updated to this:
const initialTagData = useService(UserActiveTags);
const [tagData, setTagData] = useState(initialTagData);
useEffect(() => {
setTagData(initialTagData);
}, [initialTagData]);
I think you could something like this,
In your useEffect(),
const result = await axios.post('/user/activetag');
const filteredTags = tagData.map((e) => {
const checkActive = result.data.some(i => i.tag_id == e.key);
if(checkActive){
const temp = {...e};
temp.active = 1;
return temp;
}
return e;
});
setTagData(filteredTags);
Hope that works!

Rendering an icon if condition is correct

I am trying to render an icon only if collection.masterAssetId === asset.id. I am using a getMaster function to find the collection.masterAssetId. The problem that I am having is that the collectionsarr can be undefined in my getMaster function, but also return a number. I have this error: Uncaught TypeError: Cannot read property 'masterAssetId' of undefined. Would be great if someone could fix this error for me?
Secondly, I am probably making this way too complicated, so feel free to suggest a different approach.
App.js
import React from 'react';
import './App.css';
import {collections} from "./data.js"
import {assets} from "./data.js"
import {FontAwesome, FaStar} from "react-icons/fa"
class App extends React.Component {
constructor() {
super()
this.state = {
collectionsarr: collections,
assetsarr: assets,
clickedassets: []
}
}
getMasterId(assetnr){
const assetnum = ""
if(this.state.collectionsarr.filter(element => element.masterAssetId === assetnr) === undefined){
const assetnum = 0
} else {
const assetnum = this.state.collectionsarr.filter(element => element.masterAssetId === assetnr)[0].masterAssetId
}
return assetnum
}
render(){
return (
<div className="App">
<h1>Sitecore coding challenge</h1>
<div className="left">
{this.state.collectionsarr.map(element =>
<div key={element.id}>
<p onClick={()=>this.handleAssetsClick(element.id)}>{element.name}</p>
<img src={this.getAssetPath(element.masterAssetId)} alt="pic"/>
<br></br>
</div>
)}
</div>
<div className="right">
{this.state.clickedassets.map(asset =>
<div key={asset.id}>
<img src={require(`./${asset.path}`)} alt="pic"/>
<p>{asset.name}</p>
<p>{asset.id}</p>
<button onClick={() => this.makeMaster(asset.id)}>Make master!</button>
<p>icon "this is the master</p>
{asset.id === this.getMasterId(asset.id) && <FaStar />}
<br></br>
</div>
)}
</div>
</div>
)
}
}
export default App
data.js
const collections = [
{
id: 1,
name: "The Simpsons",
masterAssetId: 13,
tags: {
name: "Cartoon",
subTag: {
name: "Simpsons family",
subTag: {
name: "2014",
},
},
},
},
{
id: 2,
name: "Super heroes",
masterAssetId: 24,
tags: {
name: "DC Super heroes",
subTag: {
name: "2014",
},
},
},
{
id: 3,
name: "Toy story",
masterAssetId: 31,
tags: {
name: "Disney",
subTag: {
name: "Pixar",
subTag: {
name: "Original movie",
subTag: {
name: "2010",
},
},
},
},
},
{
id: 4,
name: "Ninjago",
masterAssetId: 42,
tags: {
name: "Ninja",
subTag: {
name: "Secret Ninja Force",
subTag: {
name: "2017",
},
},
},
},
];
const assets = [
{
id: 11,
name: "Homer Simpson",
path: "Homer.jpg",
collectionId: 1,
},
{
id: 12,
name: "Lisa Simpson",
path: "Lisa.jpg",
collectionId: 1,
},
{
id: 13,
name: "Bart Simpson",
path: "Bart.jpg",
collectionId: 1,
},
{
id: 14,
name: "Marge Simpson",
path: "Marge.jpg",
collectionId: 1,
},
{
id: 15,
name: "Grampa Simpson",
path: "Grampa.jpg",
collectionId: 1,
},
{
id: 16,
name: "Maggie Simpson",
path: "Maggie.jpg",
collectionId: 1,
},
{
id: 21,
name: "Green Lantern",
path: "Green lantern.jpg",
collectionId: 2,
}
];
Is the collections data being set properly? What's the console.log() output of the state at render?
At any rate, I think the better approach for setting state is to do it in componentDidMount() lifecycle method:
import {getCollection} from "./data.js";
state = {
collectionsarr: [],
assetsarr: [],
clickedassets: []
},
componentDidMount = () => {
this.setState({
collectionsarr: getCollection()
});
}
data.js:
const collections = [...];
export function getCollection() {
return collections;
}
Change your getMasterId function
showIcon(assetnr) {
let index = (this.state.collectionsarr || []).findIndex(item => {
return item.masterAssetId === assetnr;
})
return index != -1;
}
This function will return true if assetId === masterId then You can render it as
{this.showIcon(asset.id) && <FaStar />}

Cannot read property 'indexOf' of undefined - react-sortable-hoc

I'm trying to get the structure below.
https://imgur.com/NBRGlhM
Three columns, with titles, and column cards that can be moved within only one column. this.state.item ['lists'] moving to the component SortableList. Then iterates after items.map ((item, index) => and moves to the component SortableItem. Then iterates aftervalue.listItems and wants to display the title of columns and cards in the column. I get the error:
Cannot read property ' indexOf 'of undefined
Demo here: https://stackblitz.com/edit/react-jpszoq
import {SortableContainer, SortableElement} from 'react-sortable-hoc';
import arrayMove from 'array-move';
const SortableItem = SortableElement(({value}) => {
return(
value.listItems.map((it, index) => {
<li>{it.title}</li>
})
)
})
const SortableList = SortableContainer(({items}) => {
console.log(items)
return (
<ul>
{
items.map((item, index) =>
<div>{item.name}
<SortableItem key={`item-${item.id}`} index={index} value={item} />
</div>
)
}
</ul>
);
});
class App extends Component {
constructor() {
super();
this.state = {
item: {
id: "abc123",
name: "AAA",
lists: [
{
id: "def456",
list_id: "654wer",
title: 'List1',
desc: "description",
listItems: [
{
id: "ghj678",
title: "ListItems1",
listItemsId: "88abf1"
},
{
id: "poi098",
title: "ListItems2",
listItemsId: "2a49f25"
}
]
},
{
id: "1ef456",
list_id: "654wer",
title: 'List 2',
desc: "description",
listItems: [
{
id: "1hj678",
title: "ListItems3",
listItemsId: "18abf1"
},
{
id: "1oi098",
title: "ListItems4",
listItemsId: "1a49f25"
}
]
},
{
id: "2ef456",
title: 'List 3',
list_id: "254wer",
desc: "description",
listItems: [
{
id: "2hj678",
title: "ListItems5",
listItemsId: "28abf1"
},
{
id: "2oi098",
title: "ListItems6",
listItemsId: "234a49f25"
}
]
}
]
}
};
}
onSortEnd = ({oldIndex, newIndex}) => {
this.setState(({lists}) => ({
lists: arrayMove(lists, oldIndex, newIndex),
}));
};
render() {
return <SortableList items={this.state.item['lists']} onSortEnd={this.onSortEnd} />;
}
}
you're missing a return on L14 in the function passed to listItems.map. Alternatively, you could remove the braces.

Categories

Resources