I have a list of results, and each time I click on a result, it calls my addFunc function to add that particular result's details as an object in the selectedData list. Currently, this works when I console.log my selectedData list.
What I want to do is display my selectedData list, and each time a result is clicked, the object will be added to the list, and I want that to be reflected on my screen.
I believe I have to use state to do this, but I am not very sure how to. Thank you for your help.
A summary of my code is below:
let selectedData = [];
const Wrapper = cb => {
return (res, triggerClickAnalytics) => (
<RenderItem
res={res}
triggerClickAnalytics={triggerClickAnalytics}
addFunc={cb}
/>
);
};
class Search extends Component {
constructor(props) {
super(props);
this.addFunc = this.addFunc.bind(this);
}
addFunc(resultdata) {
selectedData = [...selectedData, resultdata]
console.log(selectedData)
}
render() {
return (
<ReactiveList
componentId="results"
dataField="_score"
pagination={true}
react={{
and: ["system", "grouping", "unit", "search"]
}}
size={10}
noResults="No results were found..."
renderItem={Wrapper(this.addFunc)}
/>
</ReactiveBase>
);
}
}
const RenderItem = ({ res, triggerClickAnalytics, addFunc }) => {
let { unit, title, system, score, proposed, id } = {
title: "maker_tag_name",
proposed: "proposed_standard_format",
unit: "units",
system: "system",
score: "_score",
id: "_id"
};
const resultdata = { id, title, system, unit, score, proposed };
return (
<Button
shape="circle"
icon={<CheckOutlined />}
style={{ marginRight: "5px" }}
onClick={() => addFunc(resultdata)}
/>
);
};
The whole code is in this code sandbox: https://codesandbox.io/s/little-framework-spg1w
EDIT:
I've managed to change my function to a state by editing my code as such:
constructor(props) {
super(props);
this.addFunc = this.addFunc.bind(this);
this.state = { selectedData:[] }
}
addFunc(resultdata) {
var joined = this.state.selectedData.concat(resultdata);
this.setState({ selectedData: joined })
console.log(joined)
}
I now need to display the results in my joined array on the screen. How do I do this?
selectedDataneeds to be state. It cannot be declared outside like that (unless you want impossible to debug situations to arise).constructor() { this.state = { selectedData:[] } }joinedarray be displayed on the screen and update whenever I add an object to it?