In my app
there's a component that renders (play)lists
(I have 2 lists hardcoded )
I can Add a new list to the list of lists.
When you click on a list
the list of songs is displayed, and at the bottom of the list is
a button that, when you click it, displays a form with inputs (title,artist,album).
Before I fixed the adding list functionality, songs were added to the 'active' list
but now
the action is dispatched (ADD_SONG) and shows up with the right values in the (Redux)state but it renders the same type of element/component as the list and is not appened/added...
I'm not sure where to look
I hope someone can spot my faulty logic
AddSongForm
export default class AddSongForm extends React.PureComponent {
constructor() {
super();
this.state = {
clicked: false
};
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({
clicked: !this.state.clicked
})
}
handleChange = (event) => {
const value = event.target.value
const name = event.target.name
// console.log(name, value)
// console.log(this.state);
this.setState({
[name]: value
})
}
handleSubmit = (event) => {
event.preventDefault()
console.log(this.state);
if (this.state.title && this.state.artist) {
this.props.addSong({
title: this.state.title,
artist: this.state.artist,
album: this.state.album
})
}
}
render() {
return (<div>
<button onClick={this.handleClick}><h2>New Song+</h2></button>
{this.state.clicked ?
<form onSubmit={this.handleSubmit}>
<label>
Song Title:
<input type="text" name="title" onChange={this.handleChange} />
</label>
<label>
<br/> Artist:
<input type="text" name="artist" onChange={this.handleChange} />
</label>
<label>
<br/> Album:
<input type="text" name="album" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
: null}
</div>)
}
}
AddSongFormContainer
import AddSongForm from './AddSongForm'
import { connect } from 'react-redux'
class AddSongFormContainer extends React.PureComponent {
addSong = (song) => {
this.props.dispatch({
type: 'ADD_SONG',
payload: {
id: Math.ceil(Math.random()*10000),
...song
}
})
}
render() {
return <AddSongForm addSong={this.addSong} />
}
}
export default connect(null)(AddSongFormContainer)
Reducer with initial state
const initState = [
{
id: 1,
title: 'Play list 1',
data: [
{
id: 1,
title: 'DogHeart II',
artist: 'The Growlers',
album: 'Gilded Pleasures'
}, {
id: 2,
title: 'Beast of No nation',
artist: 'Fela Kuti',
album: 'Finding Fela'
}, {
id: 3,
title: 'Satellite of love',
artist: 'Lou Reed',
album: 'Transformer'
}
]
}, {
id: 2,
title: 'Play list 2',
data: [
{
id: 1,
title: 'Whatever happend to my Rock and Roll',
artist: 'BlackRebelMoterCycleClub',
album: 'B.R.M.C'
}, {
id: 2,
title: 'U Sexy Thing',
artist: 'Crocodiles',
album: 'CryBaby Demon/ U Sexy Thing'
}, {
id: 3,
title: 'Oh Cody',
artist: 'NoBunny',
album: 'Raw Romance'
}
]
}
]
const reducer = (state = initState, action = {}) => {
switch (action.type) {
case 'ADD_LIST':
return [
...state,
action.payload
]
case 'ADD_SONG':
return [
...state,
action.payload
]
default:
return state
}
}
export default reducer
PlayList Component mapping over al the songs in the list
export default class PlayList extends React.Component{
constructor() {
super()
this.state = {
clicked: false
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
clicked: !this.state.clicked
})
console.log(this.props.selectList.name)
}
render(){
// console.log(this.props);
// console.log(this.props.playLists[0].data);
return (<div>
<button onClick={this.handleClick}><h1>{this.props.playLists.title}</h1></button>
{this.state.clicked ?
<ul>
{ this.props.playLists.data.map(song =>
<li key={song.id} onClick={() => this.props.selectSong(song.id)}>
<b>{song.title}</b><br/>
By:
<br/>
<h3><b>{song.artist}</b></h3><br/>
Appears on:
<b>{song.album}</b><br/><br/>
</li>
) }
<AddSongFormContainer/>
</ul>
: null}
</div>)
}
}
Container for al the playlists in the initialstate(array)
class PlayListsContainer extends React.PureComponent {
selectSong = (id) => {
this.props.dispatch({
type: 'SELECT_SONG',
payload: id
})
}
selectSong(id) {
console.log('selected song:', id)
}
selectList = (id) => {
this.props.dispatch({
type: 'SELECT_LIST',
payload: id
})
}
selectList(id) {
console.log('selected song:', id)
}
render() {
const playlistsArray = this.props.playLists
// console.log(playlistsArray)
return (
playlistsArray.map((playlist) => <PlayList
playLists={playlist}
selectSong={this.selectSong}
selectList={this.selectList}
key={playlist.id}
/>)
)
}
}
const mapStateToProps = (state) => {
// console.log(state.playLists);
return {
playLists: state.playLists
}
}
export default connect(mapStateToProps)(PlayListsContainer)
With your comment describing your redux problems, and the screenshot of the Redux dev tools - the problem is clear now.
When you are adding a song, you are simply adding it to the top level of the store, without actually adding it to a play list.
It would be entirely possible to fix this as is. In your reducer, rather than adding the song like you do now, you need to add it specifically to a playlist. If you need a code example, I can provide one.
However, I encourage you to refactor your redux store - and follow the best practicing of having a normalized, flat state.
What this means is, you want to have two top-level objects for your redux store.
playlists
songs
Rather than including all of the data about a song in a playlist, you simply reference the id of the songs.
Your playlists would look like this:
playlists {
1: {
title: 'my playlist'
songs: [1,2,3]}
And the songs can stay the same.
Whenever you add a song to a playlist, you simply add the song, and then update the playlist with the new song id.
Another practice you can do, to make your code a bit cleaner is to use mapDispatchToProps rather than defining your redux action dispatches inline. Docs for that are here.
#
To fix the code as is, the main thing we need to do is pass along the playlistid that you want to add the song to. Otherwise, how else will we know where to put the song?
First, update your action in your addSongFormContainer to accept an additional argument, targetPlaylist (that the song will go into)
addSong = (song, targetPlaylist) => {
this.props.dispatch({
type: 'ADD_SONG',
payload: {
playlist: targetPlaylist
id: Math.ceil(Math.random()*10000),
...song
}
})
}
The usage of this action now requires you pass along a target playlist. For brevity, I am going to hardcode that the song is being added to playlist 1. I'll leave the exercise of passing the selected playlist down to the component up to you.
I cleaned up the handleSubmit to make it more clear, by moving the song into it's own variable as well.
handleSubmit = (event) => {
event.preventDefault()
console.log(this.state);
if (this.state.title && this.state.artist) {
let song = {
title: this.state.title,
artist: this.state.artist,
album: this.state.album
}
let selectedPlayList = 1 //Fix this later :)
this.props.addSong(song, selectedPlayList)
}
}
Now the last problem is the reducer.
case 'ADD_SONG':
const index = store.getState().findIndex(playlist => playlist.id ===
action.payload.playlist)
console.log(index) //This should be index 0, after looking up playlist id: 1
const updatedPlaylistSongs = this.state[index].data
updatedPlaylistSongs.push(action.playload.song)
return [
...state.slice(0, index), // All playlists before current
{
...state[index], //The targeted playlist.
...updatedPlaylistSongs //The updated songs
},
...state.slice(index + 1), //All playlists after current
]
I hope the reducer works for you, though it might need a bit of work - I am not used to writing reducers dealing with arrays. I typically have normalized data, which results in much easier modification. I highly encourage you to attempt to normalize your redux store. Stop using arrays, try using objects where the key is generated (use uuidv4 to make a unique & random key). This makes "selecting" what you want to edit/update significantly easier.
I hope this helps!
Related
I have a list of od dicts. It looks like this:
document.__moreComments = [
{ id: 2, author: '...', text: '...', date: '...' },
{ id: 1, author: '...', text: '...', date: '...' },
];
I want to sort my data by date and rendered it.
Firstly I want to create an object in the declaration and set it in state. Then sorting and represent changing data. I have a problem.
import React, { Component } from "react";
var addcomments = document.__moreComments;
class AdditionalComments extends Component {
constructor() {
super();
// this.state = addcomments
this.state = {
comments: addcomments.map(addcomment => [
addcomment.id,
addcomment.author,
addcomment.text,
addcomment.date
])
};
console.log(this.state);
}
changeMessage() {
let sortedComments = this.state.comments;
this.setState({
comments: sortedComments.sort((a, b) => a.date > b.date)
});
console.log(this.state.comments);
}
render() {
return (
<div>
<h1>hi Eugene {this.state.comments} </h1>
<button onClick={() => this.changeMessage()}>Click</button>
</div>
);
}
}
export default AdditionalComments;
I create dict of dict. And of course I want to know. Is it right to do what I do or I need another approach?
Thanks. I'm a beginner.
Sort sorts array in-place(that means it won't return new instance of array), that's the reason your array is not getting sorted. You should try below approach:
changeMessage() {
let sortedComments = [...this.state.comments].sort((a,b) => new Date(a.date) - new Date(b.date))
this.setState({
comments: sortedComments
}, () => {console.log(this.state.comments)});
}
I'm trying to push in elements into an array called 'this.state.tags'. On the console, I see the elements pushing into the array. However, when I add something, the array comes out blank, when I add more items I only the see the previous items I've added. I'm not seeing the newest item I've pushed in.
I've done Object.assign([], this.state.tags) from the child component Grades.js. Then I pushed in 'this.state.newTag' and I've reset the state to that new result.
//From Grades.js, the child component
state = {
toggle: null,
newTag: '',
tags: []
}
addTags = (event) => {
event.preventDefault();
let newTagArr = Object.assign([], this.state.tags)
newTagArr.push(this.state.newTag)
this.setState({
tags: newTagArr
})
// this will pass on to the parent
this.props.filterTags(this.state.tags)
}
render() {
const { tags } = this.state
let tagList = tags.map((item, index) => {
return (
<li key={index} className="tagListItem">{item}</li>
)
})
return(
<div>
<ul className="tagList">{tagList}</ul>
<form onSubmit={this.addTags}>
<input
placeholder="Add a tag"
name="newTag"
onChange={this.handleInput}
style={{border: '0', borderBottom: '1px solid #000'}}
/>
</form>
</div>
)
}
// From App.js, the parent component
state = {
students: [],
filteredStudents: [],
filteredByTag: [],
search: '',
tag: '',
toggle: false
}
componentDidMount() {
axios.get('https://www.hatchways.io/api/assessment/students')
.then(result => {
let newArr = Object.assign([], result.data.students);
let newResult = newArr.map(elem => {
return {city: elem.city, company: elem.company, email: elem.email,
firstName: elem.firstName.toLowerCase(), lastName: elem.lastName.toLowerCase(),
grades: elem.grades, id: elem.id, pic: elem.pic, skill: elem.skill}
})
this.setState({
students: newResult
})
})
.catch(err => console.log(err))
}
tagFiltering = (param) => {
console.log(param)
this.state.students.push()
}
I expect the output to be ["tag1", "tag2", "tag3"]
Not ["tag1", "tag2"], when I've already typed in tag1, tag2 and tag3
Use ES2015 syntax :
this.setState({
tags: [...this.state.tags , this.state.newTag]
})
In react the state is immutable meaning that we have to provide new state object every time, we call the setState method.
I have the following Array
arrayOfItems: [{
0:
description: "item1"
id: 11
name: "item1Name"
},
1:
description: "item2"
id: 12
name: "item2Name"
},
2:
description: "item3"
id: 13
name: "item3Name"
},
3:
description: "item4"
id: 14
name: "item4Name"
}]
I want to add a new pair
{
description: "item5"
id: 15
name: "item5Name"
}
I am still very new to React and have been working on this problem. I do understand how Map works but not sure how I can add new pair in React
This component is a dropdown list so there is no input or button click related to it.
{dataArray.arrayOfItems!.map((item: any) => {
return (
<ComponentName key={item.id} value={item.description}>
{item.description}
</ComponentName>
);
})}
if you want to add item to array on page load use componentDidMount() method:
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
items:[
{id:1,name:'aaa', description:'this is description aaa'},
{id:2,name:'bbb', description:'this is description bbb'},
]
}
}
componentDidMount(){
let items=this.state.items;
let newItem={id:5,name:'ccc',description:'this is description ccc'};
let updatedItems=items.push(newItem);
// or you can use ... spread operator
// let updatedItems=[...items,newItem];
this.setState({items:updatedItems});
}
}
You can store your array into state, and then modify the state.
Here's an example
function MyComponent() {
const [items, setItems] = React.useState([{ id: 0, description: 'Old Item' }])
const loadMoreItems = () => {
setItems([...items, { id: 1, description: 'New Item' }])
}
return (
<>
{items.map((item) => (
<div key={item.id} value={item.description}>
<p>{item.description}</p>
</div>
))}
<button onClick={loadMoreItems}>Load more items</button>
</>
)
}
Add on change event to your dropdown.
onChange = (event) => {
console.log(event.target.value)
// add your value to array here
this.setState((prevState) => {
arrayOfItems: [...prevState.arrayOfItems, yourItem],
})
}
<select onChange={this.onChange}>
</select>
EDIT
Adding values on page load. Don't use push to add items to array in state.
componentDidMount = () => {
this.setState((prevState) => {
arrayOfItems: [...prevState.arrayOfItems, yourItem],
})
}
let fileInfos=this.state.fileInfos;
fileInfos.push({
"name": file.name,
"content": e.target.result
});
this.setState({fileInfos});
I am maintaining an array of objects which is stored in a state object. Basically I am pushing each object to this array whenever I click on Add button .This stores this object in array.
Also I am iterating this array of objects to display down the page.
Right now I am trying to fill the input fields based on the object that I have clicked. I am unable to do it. Basically, the object that I have clicked should populate the input fields and then I should be able to edit it
Help would be appreciated
The structure of array of objects:
users= [
{"name":"xxx","email":"yyy","phone":"656"},
{"name":"yyy","email":"xxx","phone":"55"}
];
Component Code
import * as React from 'react';
interface IState{
users : Account[];
user: Account
}
interface Account{
name: string;
email: string;
phone: string
}
export default class App extends React.Component<{},IState> {
constructor(props:any){
super(props);
this.state= {
users: [],
user: {
name: '',
email: '',
phone: '',
}
}
}
removeAccount = (i:number) => {
let users = [...this.state.users];
users.splice(i,1);
this.setState({users},()=>{console.log('setting the data')});
}
handleChange = ( event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({
user:{
...this.state.user,
[event.currentTarget.name]:event.currentTarget.value
}
})
}
onAdd = () => {
e.preventDefault();
this.setState({
users: [...this.state.users, this.state.user],
user: { name:'', email: '', phone: ''}
},()=>{console.log('adding')});
}
clearInputs = () => {
this.setState({user: { name:'', email: '', phone: ''}});
}
showDetails = (i:number) => { //I need to populate the input fields based on the index of the object clicked.
console.log(i);
}
render(){
const { name, email, phone } = this.state.user;
<React.Fragment>
<form onSubmit={this.onAdd}>
<input type="text" value={name} onChange={(e:any) => this.handleChange(e)} name={"name"} />
<input type="text" value={email} onChange={(e:any) => this.handleChange(e)} name={"email"} />
<input type="text" value={phone} onChange={(e:any) => this.handleChange(e)} name={"phone"} />
<button type="submit">Add</button>
</form>
<ul>
{this.state.users.map((row:any ,index: number) =>
<li key={index}>
<a onClick={()=> this.showDetails(index)}><span>{row.name}</span></a> // on click of this,i need to display the values corresponding to this object in the above input fields
<i className="close far fa-times" onClick={() =>this.removeAccount(index)}/>
</li>
)}
</ul>
</React.Fragment>
}
}
Based on logic of the code showDetails should look like
showDetails = (i:number) => {
this.setState ({user: this.state.users.splice(i,1)});
console.log(i);
}
Just set user to the selected element of users array. React will do update and calls render() with updated data.
Also utilizing splice will remove currently editing user from array. THis follow logic of the code. After edit Add should be clicked to add modified user back to array. This may be not convenient, so you may consider adding editingIndex to state and specify which user object currently editing. In such case you'll have to save index of selected object in editingIndex. In handleChange you should check if some user object editing now and modify data not only in user property of state but in corresponding users array element
interface IState{
users : Account[];
user: Account;
editingIndex: number | null;
}
// In constructor
constructor(props:any){
super(props);
this.state= {
users: [],
user: {
name: '',
email: '',
phone: '',
},
editingIndex: null
}
}
showDetails = (i:number) => {
this.setState ({user: this.state.users[i], editingIndex: i});
console.log(i);
}
handleChange = ( event: React.ChangeEvent<HTMLInputElement>) => {
let user = {...this.state.user,
[event.currentTarget.name]:event.currentTarget.value};
this.setState({user});
// If we currently editing existing item, update it in array
if (this.state.editingIndex !== null) {
let users = [...this.state.users];
users[this.state.editingIndex] = user;
this.setState({users});
}
}
removeAccount = (i:number) => {
let users = [...this.state.users];
// If we're going to delete existing item which we've been editing, set editingIndex to null, to specify that editing ends
if (this.state.editingIndex === i)
this.setState({user: {name: '', email: '', phone: ''}, editingIndex: null});
users.splice(i,1);
this.setState({users},()=>{console.log('setting the data')});
}
onAdd = () => {
e.preventDefault();
// If we NOT editing, but adding new editingIndex will be null so add user to users array. If we editing existing element it's no need to add it once again.
if (this.state.editingIndex === null)
this.setState({ users: [...this.state.users, this.state.user] });
this.setState ({ editingIndex: null,
user: { name:'', email: '', phone: ''}
},()=>{console.log('adding')});
}
// render will have no change
I have a table, it's first three rows are hardcoded. After first three rows I want to add new objects in table. I write code for it but when I enter new data my old data is erase from table and new data is appear. I want it at its place and wants to add new data exactly after it. Here is the code of my state
constructor(props)
{
super(props)
{
this.state={
id:'',
name:'',
birth:'',
data:[
{
id:'1',
name:'Muhammad Ali jinnah',
dateofBirth:'1876'
},
{
id:'2',
name:'Allama Iqbal',
dateofBirth:'1877'
},
{
id:'3',
name:'Ahmad Bilal',
dateofBirth:'1992'
}
],
}
}
in that state i have array of objects i have hardcoded and state for data which i used to get data from my input box..input box are used to get data from user and add data in table and submit used to add data in table by using function..
here is code for my handle submit where i want to setstate for new object
handleSubmit(event) {
console.log('A ID:name and birth was submitted: ' + this.state.id,this.state.name,this.state.birth);
const { id, name, birth } = this.state;
const newdata = {
id: id,
name: name,
dateofBirth: birth
};
this.setState(prevState => ({
data: [prevState.data,newdata ]
}));
console.log("new array",this.state.data)
event.preventDefault();
}
I want to change its state but i also want my first three rows as i hardcoded
The error is occurring because you are not using the spread operator for inserting into the array.
When you use something like:
this.setState(prevState => ({
data: [prevState.data,newdata ] //This is wrong
}));
prevState.data becomes the first element of new array and new data becomes the second, instead you can use the spread operator for new array like:
this.setState(prevState => ({
data: [...prevState.data,newdata ]
}));
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
id: "",
name: "",
birth: "",
data: [
{
id: "1",
name: "Muhammad Ali jinnah",
dateofBirth: "1876"
},
{
id: "2",
name: "Allama Iqbal",
dateofBirth: "1877"
},
{
id: "3",
name: "Ahmad Bilal",
dateofBirth: "1992"
}
]
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
console.log('A ID:name and birth was submitted: ' + this.state.id,this.state.name,this.state.birth);
const { id, name, birth } = this.state;
const newdata = {
id: id,
name: name,
dateofBirth: birth
};
this.setState(prevState => ({
data: [...prevState.data,newdata ]
}));
console.log("new array",this.state.data)
event.preventDefault();
}
render() {
return (
<main>
<form onSubmit={this.handleSubmit}>
<input name='id' type='number' value={this.state.id} onChange={this.handleInputChange} placeholder='ID' />
<input name='name' value={this.state.name} onChange={this.handleInputChange} placeholder='Name' />
<input name='birth' type='date' value={this.state.birth} onChange={this.handleInputChange} placeholder='Date of Birth' />
<button type='submit'>Add New</button>
</form>
<table className='content'>
<tbody>
{
this.state.data.map(item=>{
return (
<tr>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.dateofBirth}</td>
</tr>
);
})
}
</tbody>
</table>
</main>
);
}
}
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"></div>
Following is the pseudo code that should solve your issue.
const prevData = this.state.data;
// Make first 3 are not overridden
var preserved = prevData.splice(3)
preserved.push(...newData)
this.setState({ data : preserved});
If I'm understanding correctly... You should be able to create a render with 3 static rows, then dynamically append rows based on the object you have in state (this.state.data). See below for example.
render {
return (
<table>
<tr><td>sample1</td></tr>
<tr><td>sample2</td></tr>
<tr><td>sample3</td></tr>
{
this.state.data.map((dataElement) => {
<tr><td>{dataElement.name}</td></tr>
});
}
</table>
)
}
let temp=this.state.data;
temp=temp.push(newdata)
Add these lines into your handleSubmit() and set temp into your state by using setState method.