React - update object in state - reactjs

I need to update an object in state, but only some of its elements. So if it has 7 elements, and my new object has 4, those 4 should replace the existing ones while the rest should be preserved.
Here is an example component which outputs the current object keys and values in the state. When you press the button, the object should get updated with new values on some of its properties. Right now it is overwriting the object with the 4 elements, so I need to modify it. See the handleClick method.
In my real project the object is inside redux state, but I guess the solution will be the same. I get the new properties from a form that is posted, so I have an object like the one below named "update".
import React, { Component } from 'react';
import Button from 'material-ui-next/Button';
import Menu, { MenuItem } from 'material-ui-next/Menu';
class UpdateObject extends Component {
constructor(props) {
super(props)
this.state = {
theObject : {
token: '478478478478',
firstName: 'Goofy',
lastName: 'Hello',
age: '14',
sex: 'female',
employed: true,
favoriteColor: 'Blue',
bio: 'details of bio',
}
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
let update = {
age: '40',
lastName: 'Newname',
employed: true,
favoriteColor: 'Yellow',
}
let change = Object.assign({}, this.state.theObject);
change = update;
this.setState({ theObject: change });
}
render() {
const myObj = this.state.theObject;
return (
<div className="updateobjectwrapper bl">
<div> Here is the current object: <br />
<ul>
{ Object.entries(myObj).map(([ key,value ] ) => {
return (
<li key={key}>{key} : {value} </li>
)
})
}
</ul>
</div>
<Button
onClick={this.handleClick}
>
Update Object
</Button>
</div>
)
}
}

You can pass multiple arguments to Object.assign method and it will merge all of them.
handleClick(){
let update = {
age: '40',
lastName: 'Newname',
employed: true,
favoriteColor: 'Yellow',
}
let change = Object.assign({}, this.state.theObject, update);
this.setState({ theObject: change });
}

Related

Error - PrimeReact Autocomplete suggestions not showing

https://primefaces.org/primereact/showcase/#/autocomplete
I am trying to load suggestions dropdown as soon as component loads with some data in componentDidMount. The suggestionsList is updating with the obj data in componentDidMount, however suggestion dropdown is not showing.
Simply, whenever input is get focussed and no input text is there, a suggestion dropdown should show.
abcCmp.jsx
class abcCmp extends React.Component {
state;
constructor() {
super();
this.state = {
suggestionsList: []
};
}
componentDidMount() {
let obj = [{'color':'red',name: 'Danny', id: '1'}];
this.setState({suggestionsList: [...obj]})
}
render(){
return (
<div className="containerBox">
<AutoComplete suggestions={this.state.suggestionsList}
minLength={1} placeholder="Add People" field="name" multiple={true}
autoFocus={true} />
</div>
)
}
If you gone through documentation there are other parameters also required.
Those are: completeMethod,value,onChange out of these completeMethod is required to show filtered list as you type. Inside completeMethod you need to filter your data that's how your dropdown list reduces as you type more.
You need ref for toggling dropdown functionality and also you need to check on focus if input value is empty and no value is selected so toggle dropdown.
Here is simple POC I create for reference. Try typing D
Code:
import React from "react";
import { AutoComplete } from "primereact/autocomplete";
import "./styles.css";
let obj = [
{ color: "red", name: "Dagny", id: "1" },
{ color: "red", name: "kanny", id: "2" },
{ color: "red", name: "Dgnny", id: "3" },
{ color: "red", name: "Danny", id: "4" },
{ color: "red", name: "Dmnny", id: "5" },
{ color: "red", name: "Donny", id: "" }
];
class MyComponent extends React.Component {
myRef = React.createRef();
constructor() {
super();
this.state = {
suggestionsList: [],
selected: null,
inputValue: null
};
}
componentDidMount() {
this.setState({ suggestionsList: [...obj] });
}
searchList = (event) => {
let suggestionsList;
if (!event.query.trim().length) {
suggestionsList = [...obj];
} else {
suggestionsList = [...obj].filter((list) => {
return list.name.toLowerCase().startsWith(event.query.toLowerCase());
});
}
this.setState({ suggestionsList });
};
render() {
return (
<div className="containerBox">
<AutoComplete
suggestions={this.state.suggestionsList}
completeMethod={this.searchList}
minLength={1}
ref={this.myRef}
dropdown
inputId="my"
placeholder="Add People"
field="name"
onFocus={(e) => {
if (!this.state.inputValue && !this.state.selected) {
this.myRef.current.onDropdownClick(e, "");
}
}}
onKeyUp={(e) => this.setState({ inputValue: e.target.value })}
// completeOnFocus={true}
multiple={true}
autoFocus={true}
value={this.state.selected}
onChange={(e) => this.setState({ selected: e.value })}
/>
</div>
);
}
}
export default function App() {
return (
<div className="App">
<MyComponent />
</div>
);
}
Demo: https://codesandbox.io/s/prime-react-autocomplete-forked-n3x2x?file=/src/App.js
Add dropdown inside autocomplete tags and also add completeMethod and bind it to a search/filter function, add a value to bind the selected value, add a onChange function to it
You can find full documantation and working example here :PrimeFaces React Autocomplete

how to push a new element into an array from the state

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.

Want to populate the input values based on the click of an object inside map(): React+Typescript

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

Hide an element in multiple elements by react

I want to hide an element by react in multiple elements. I try to use isHidden: true, but when i click the close button instead of hiding selected element, gives me a full blank page ? why?
class App extends React.Component {
constructor(props){
super(props);
this.state = {
data: [
{ _id: "5bb85a2be138230670c3687b", firstName: "foo", lastName: "foo", email: "foo#foo.com"},
{ _id: "5bb9b3cae13823261e886990", firstName: "bar", lastName: "bar", email: "bar#bar.com" },
],
editVisibles: {},
isHidden: true,
};
}
showEditDiv = (_id) => {
this.setState( prevState => ({
editVisibles: { ...prevState.editVisibles, [_id]: !prevState.editVisibles[_id] }
})
)
};
toggleHidden = ()=> this.setState((prevState)=>({isHidden: !prevState.isHidden}))
renderFlight() {
return this.state.data.map(item => {
return (
<div>
{this.state.isHidden &&
<li key={item._id}>
<div class="close" onClick={() => this.toggleHidden(item._id)}>X</div>
<p>{item.email}</p>
<button onClick={() => this.showEditDiv(item._id)}>Edit</button>
<div key={item._id} className={`edit-form ${!this.state.editVisibles[item._id] ? "unvisible" : "visible"}`}>
</div>
</li>
}
</div>
)
})
}
render() {
return (
<div>{this.renderFlight()}</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
First of all, the code is really messy and hard to read, so you should edit it for better visibility.
Also, notice that isHidden is true when the element should not be visible, but your code states that "if this.state.isHidden is true, then render the content of the div".
What you want is !this.state.isHidden && ...
Also, you should use reduce/filter to filter out the elements that have a truthy value for isHidden, instead of map, because right now you're pushing empty div elements which is unnecessary
Could see an argument in your method call - this.toggleHidden(item._id), but item._id is not used in the function definition. Any particular reason for that?
toggleHidden = ()=>
this.setState((prevState)=>({isHidden: !prevState.isHidden
}))
Basically we have to select the item by keyProp and apply the toggle method. Go through
How to find element by Key in React?
<li keyProp={'listItem_'+item._id}>
would give the necessary attribute and we can apply show/hide on the li element by selecting using props.keyProp

ADD_SONG not added to PlayList

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!

Resources