Reputation: 131
I want to have a data structure in terms of array e.g.
data[0]
title:"ABC"
photo: "./123.jpg"
summ: "text text test"
data[1]
title:"ABCD"
photo: "./1234.jpg"
summ: "text texwt test"
I have attempted to setState like this, but it won't work. Please guide me ;(
this.setState({
data:{
title: [ ...this.state.data.title, title ],
photo: [ ...this.state.data.photo, photo ],
summ: [ ...this.state.data.summ, summ ]
}
});
Uncaught (in promise) TypeError: _this.state.data.concat is not a function
///// Mistake on not initialize my state
// this is incorrect
this.state={
data:{
title:null,
photo:null,
summ:null,
}
//The correct version is
this.state={
data:[],
Upvotes: 0
Views: 175
Reputation: 1276
The reason your solution doesn't work is that you are trying to assign an object to an array.
I am not sure if you are trying to add an item to array or change single item from an array. If you are trying to add, you can do it like this:
this.setState({
...this.state.data, {title, photo, summ}
})
However if you are trying to change an item from the array. You should store in a temporary variable and then assign it like this.
const tempArray = this.state.data;
this.setState({
data: tempArray.filter(//some change function)
})
If you are trying to initialize your data into state, you can do it like this:
import JsonData from "./myJsonData"
constructor(props) {
super(props);
this.searchBarRef = React.createRef();
this.state = {
data: JsonData
};
}
Hope this solves your issue. If I couldn't explain clearly please say, so I can try to give a better answer to your problem.
Upvotes: 1
Reputation: 1679
As Felix Kling said in commentary, you want an Array of Object so you need to have a structure like that :
this.setState({
data: [
...this.state.data,
{ title, photo, summ }
];
});
Upvotes: 1