Gthu
Gthu

Reputation: 37

Can't set state in a onClick function in React Hook

Hi i cant set state in a using a function i defined for onClick. All other lines are working except setting the state.

export default function SaleProducts(props) {
     const [currentSelected, setSelected] = useState(props.location.state.pid);

     useEffect(() => {
       superagent
        .post("url")
        .set("Content-Type","application/x-www-form-urlencoded")
        .send({"access_token":token})
        .set('accept', 'json')
        .end((error, response) => {
          if(error){
            console.log("Error")
          }
          else{
            var json = response.body;
            json.products.map((res) => {
            var array = [res.title,"Not yet published",res.variants[0].price,<Button onClick={(event) => handleItemDeletion(event,res.id)}>Delete Item</Button>];
            arr.push(array);
          })
     ,[currentSelected]}

     const handleItemDeletion = (event,id) =>{
       event.preventDefault();
       var cSelected = currentSelected.replace(id,'');
       setSelected((currentSelected) => cSelected);         //this is not working
       console.log("Current Selected : ",currentSelected)        
     }

     return(<arr>);    //this is only for representation

OnClick function is getting called but only that setSelected line is not working. The state is not changing it is still like before.

Upvotes: 0

Views: 1235

Answers (2)

Alan Paul Mathew
Alan Paul Mathew

Reputation: 219

Setting the state is not correct. Try this,

export default function SaleProducts(props) {
     const [currentSelected, setSelected] = useState(props.location.state.pid);

     useEffect(() => {
       superagent
        .post("url")
        .set("Content-Type","application/x-www-form-urlencoded")
        .send({"access_token":token})
        .set('accept', 'json')
        .end((error, response) => {
          if(error){
            console.log("Error")
          }
          else{
            var json = response.body;
            json.products.map((res) => {
            var array = [res.title,"Not yet published",res.variants[0].price,<Button onClick={(event) => handleItemDeletion(event,res.id)}>Delete Item</Button>];
            arr.push(array);
          })
     ,[currentSelected]}

     const handleItemDeletion = (event,id) =>{
       event.preventDefault();
       var cSelected = currentSelected.replace(id,'');
       setSelected(cSelected);         // check here
       console.log("Current Selected : ",currentSelected)        
     }

     return(<arr>);

Upvotes: 1

Georgy
Georgy

Reputation: 1939

You should pass value to setSelected, not a function. Something like this: setSelected(cSelected);

Upvotes: 1

Related Questions