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
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 ] })
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments