Reputation: 45
class App extends Component {
constructor(props) {
super(props);
this.state = {
Foo: [],
Bar: []
};
this.xfetch('Alice', this.state.Foo);
}
xfetch = (param, target)=> {
const res = getRes(param);//db request async
//onCompleted: () => {
this.setState(({ target}) => {
const newArr = [...target, res ];
return {
target: newArr
};
});
}
addBar = input => {
this.xfetch(input, this.state.Bar);
};
the code above doesn't work, and I don't want to write multiple versions of xfetch()
for different parts of the state
*first part of the state I want to set in the constructor
Upvotes: 1
Views: 67
Reputation: 136
Try this, target has to be a string, for example "Foo"
xfetch = async (param, target) => {
const res = await getRes(param)
this.setState({ [target]: [...this.state[target], res ] })
}
this.xfetch("Alice", "Foo");
Upvotes: 1
Reputation: 7652
from what it sounds like, you are wanting to update state dynamically?
try this:
xfetch = async (param, target) => {
const res = await getRes(param)
this.setState({ [target]: [...target, res ] })
}
Upvotes: 0