Update 2D state array with 2 different strings - javascript

I've been trying to search for this in the docs but couldn't find anything
I'm trying to update my array 'myGamesArray' with the string 'query' and 'image'.
This is a multi-dimensional array and I want to update the first column with 'query' and the second column with 'image'.
I tried this here but it did not work:
constructor(props) {
super(props);
//Initialization of state
//films will contain the array of suggestion
//query will have the input from the autocomplete input
this.state = {
myGamesArray:[{name: "", img: ""}],
games: [],
query: ' ',
image: '',
};
}
this.setState(prevState => {
const { myGamesArray, query, image } = prevState;
return {
myGamesArray: [...myGamesArray[0][0], query.toString()],
myGamesArray: [...myGamesArray[0][1], image.toString()],
query:''
};
},

you should change the myGamesArray once then return it, also spread the prevState so the old values are preserved, so the could should look something like this:
this.setState(prevState => {
const { myGamesArray, query, image } = prevState;
myGamesArray.unshift({
name: query.toString(),
img: image.toString(),
});
return {
...prevState
newGameArray,
query:'',
};
},

Related

Add dynamic key to set state, react

I have this state
this.state = {
dropdown1: false,
dropdown2: false,
dropdown3: false
}
I want to access to these dropdowns in state using this.setState but the number after 'dropdown' comes from API
onMaca = (ev) => {
this.setState({
dropdown + ev: true
})
}
So I want the key to be dynamic 'dropdown1' for example.
Thanks for your answers
you can access the object property like this object['property name']
onMaca = (ev) => {
this.state['dropdown' + ev]= true;
this.setState({
...this.state
})
}
https://codezup.com/add-dynamic-key-to-object-property-in-javascript/
You can use any of these to set key dynamically. I will try to update the answer with an example in a while for setState.
The state is a JS object, so you can get its keys as usual, like so:
const stateKeys = this.state.keys()
Now you have an array: [ "dropdown1", "dropdown1", "dropdown1" ]
One way to use it would be:
const keysMap = statekeys.map(( item, i ) => return {
key: item,
idx: i,
number: item.replace( /dropdown/, '' )
}
keysMap will look like so: [ { key: 'dropdown1', idx: 0, number "1" }, { key: 'dropdown1', idx: 1, number "2" }, { key: 'dropdown1', idx: 2, number "3" } ]
You can query keysMap for a given dropDownNumber like so:
let k = keysMap.find( kmap => kmap.key = dropDownNumber )
To set the dropdown's state:
this.setState({ k: <whatever> })

React - How can I access a particular position in the array, and then change it?

In state, I have an array and would like to access one of the array positions.
For example, in other languages it might be:
usersJson[position] ...
But in the react I can't do:
this.state.usersJson[position] = ...
Can anyone help?
constructor() {
super();
this.state = {
usersJson: []
};
//loads a list of users througth jsonPlaceholder data
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(json => this.setState({ usersJson: json }));
I have tried this:
{this.state.usersJson.map((item => {
if (item.id === props.id) {
return(
item.email = props.email,
item.address = {
street: props.address.street,
suite: props.address.suite,
city: props.address.city,
zipcode: props.address.zipcode,
},
item.phone = props.phone
)
}
return null
}))}
but I want something like
this.setState({userJson[position]: ...})
The array looks like:
usersJson:{
id: ...,
name: "...",
email: "..",
address: {
street: "...",
suite: "...",
city: "...",
zipcode: "..."
},
phone: "..."
}
You can copy your array to a temporary array and then change that array. It would be something like
adjustArray = () => {
const {usersJson} = this.state;
let tempArray = [...usersJson];
tempArray[position] = "something";
this.setState = ({ usersJson: tempArray});
}
In React classes you should only update by using this.setState.
If you don't know what position of the array the user is in then you can use the .find method for arrays. However since you are trying to trying to access JSON, I recommend converting the array that you receive from the API into an object. Then you would be able to access the position with this.state.usersJson[key] where key is whatever you decide to name each object in usersJson.
To update your state based on a property name:
state = {
name : 'John',
surname : 'Doe'
}
handleChange = (name, value) => this.setState(state =>({
...state,
[name] : value
}))
render() {
const { name } = this.state
return <input value={name} onChange={e => this.handleChange('name', e.target.value))}
}

React/JavaScript: Using React spread to performing 2 changes(at the same time) on array

I am trying to rename 'timestamp' in my array with key/value pairs. Currently, I am adding id and assinging a value but I also need to change 'timestamp' to 'start'. Is it possible to do all that at once?
Here is what I have so far:
const { data } = this.state
const newAction = data.action.map((actionItem, index) => ({
...actionItem,
id: index + 1,
...actionItem,
'start': actionItem.timestamp
}));
const items = {
...data,
action: newAction
};
Data Structure:
Update:
So, instead of replacing timestamp with start, the code above adds start to array. I want timestamp to be named start.
Another approach with spread syntax.
const action = [
{
Second: [],
action: "Program Executed",
timestamp: 12345,
},
{
Second: [],
action: "Something Happened",
timestamp: 67891,
}
];
const newAction = action.map( ( actionItem, index ) => {
const { timestamp: start, ...rest } = actionItem;
return {
...rest,
id: index + 1,
start,
}
});
console.log( newAction );

Multiple Search Selection Dropdown

Tell me please, how can I set defaultValue in Multiple Search Selection Dropdown? I tried to set array of object like discribe in docs, but I do not receive what I want
constructor(props) {
super(props);
this.state = {
specs: [],
doctorSpecs: []
}
this.profileService = new ProfileService();
this.addSpecializationsService = new SpecializatoinsService();
}
componentWillMount() {
this.profileService.getProfileInformation()
.then((res) => {
this.setState({
profile: res.data,
consultationFees: res.data.consultation_fees,
mpdbRegistrationNumber: res.data.mpdb_registration_number,
qualification: res.data.qualification,
experienceYears: res.data.experience_years,
doctorSpecs: res.data.specializations.map((elem, index) => {
return {key: index, value: elem.id, text: elem.name}
})
})
})
this.addSpecializationsService.getSpecializationsList("", (res) => {
console.log(res);
this.setState({
specs: res.data.body.map((elem, index) => {
return {key: elem.id, value: elem.id, text: elem.name}
})
})
});
}
// other nessesary code
// component where must be this.state.doctorSpecs
<Dropdown
className='profile-specs'
placeholder='Skills'
fluid multiple selection search
options={this.state.specs}
onChange={this._onChangeSpecs}
value={this.state.doctorSpecs}
onSearchChange={this._getListSpecs}/>
I want , after render component, display array of values in this dropdown
I tried to use value, defaultValue, but it's not work
I find a problem.
I had to transfer to the array not objects, but text values from this objects

ReactJs - How to update state in array?

I'm creating a Page Builder with React.
I have a component which contains the structure of the page.
var LayoutPage = React.createClass({
getInitialState: function getInitialState() {
return {
items: {
'78919613':{
id: '78919613',
component : 'OneColumn',
cols:{
'565920458':{
id: '565920458',
content:{
'788062489':{
id: '788062489',
component : 'Text',
params: 'Lorem ipsum'
},
'640002213':{
id: '640002213',
component : 'Text',
params: 'Lorem ipsum'
}
}
}
}
}
}
};
},
.....
});
I have a system with drag'n drop to put a new element on the page and it works. But when the new element is dropped I want to update the state to add a new item in the array.
So how can I push a new item ? I did a test with that :
this.state.items.push({.....});
But I have an error :
TypeError: this.state.items.push is not a function
Can you help me ?
Thank you.
Instead of using an object in your state you should change it to the array like below :
this.state = {
items: [ // items array
{
id: 1,
name: "Stack"
},
{
id: 2,
name: "Overflow"
}],
count: 3, // another state
textValue : '' // and this is state too
}
Where the items it's an array of objects. And then you will be able to add new items to an array.
const newItem = {
id : this.state.count,
name: this.state.textValue
};
const newArr = this.state.items.concat(newItem);
this.setState({
items: newArr,
textValue: '',
count: this.state.count + 1
})
The whole example is here.
I hope it will help you!
Thanks
You'll start to get headaches if you directly mutate the state of your application. If you forget to call this.setState then it won't re-render!
Assuming you can't use an array (which would be easier), then you'll have to generate a unique key if you want to add another item to the object.
// create a new copy of items based on the current state
var newItems = Object.assign({}, this.state.items),
newItem = { id: '', component: '', cols: {} },
uniqueId = generateUniqueId();
// safely mutate the copy
newItems[uniqueId] = newItem;
// update the items property in state
this.setState({ items: newItems });
This is even easier with ES7/Babel.
const newItem = { id: '', component: '', cols: {} },
uniqueId = generateUniqueId(),
items = { [uniqueId]: newItem, ...this.state.items };
this.setState({ items });
You can generate a similar unique ID to the one you have there using Math.random.
function generateUniqueId() {
// removing leading '0.' from number
return Math.random()
.toString()
.slice(3);
}

Categories

Resources