Search code examples
reactjsapollo-client

update of a buttons style on call of useState. how to convert variable of an object to string?


I want to update the style of button whenever is clicked.

I can't use true/false to change the state because in query 2 objects with similar value.. so whenever one is clecked these both are getting changed style

Currently when button clicked happens nothing, except that useEffect outputs in console correct value.

It seems that this problem in const onClick, it returns value in string:
Object { thisVal: "40", thisIndex: "0" }
Object { thisVal: "40", thisIndex: 0 }

Maybe you can suggest something?

          ...

  const [thisButtomSelected, setThisButtomSelected] = useState({
    thisVal: 0,
    thisIndex: 0,
  })
   const onClick = e => {  
    setThisButtomSelected({ thisVal: e.currentTarget.value, thisIndex: e.currentTarget.id });
  }

  useEffect(() => {
    console.log(thisButtomSelected)
  }, [thisButtomSelected])

       ...

  <li id="list" key={item.id}>
    <button
      value={item.value}
      id={index}
      className={isEqual(thisButtomSelected, { thisVal: item.value, thisIndex: index }) 
        ? 'button-selected' : 'button'
      }
      onClick={onClick}
    >
      {console.log(thisButtomSelected)}
      {console.log({ thisVal: item.value, thisIndex: index })}
      {item.displayValue}
    </button>
</li>
    ...

{item.value}, {index} and so on are taken from useQuery (apollo-client) and map was used


Solution

  • Here you go:

    const onClick = e => {  
        setThisButtomSelected({ thisVal: parseInt(e.currentTarget.value), thisIndex: e.currentTarget.id });
      }