a1olegs
a1olegs

Reputation: 45

how can I reuse the function to update different parts of the state of a React component?

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

Answers (2)

Yupeng Li
Yupeng Li

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

Red Baron
Red Baron

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

Related Questions