-1

I have this code below:

const [clientID, setClientID] = useState({});

// explodeClientID is an object
let explodeClientID = ClientIDFormatter(routeParams.QRData);
// I assign that variable to me clientID state:
setClientID(explodeClientID);

// I logged the variable:
console.log("Exploded Client ID:")
console.log(explodeClientID);
/* OUTPUT: 
Exploded Client ID:
Object {
  "BR_ID": 1,        
  "ClientChkID": 4,  
  "ClientID": 599920,
} */

// I logged the state:
console.log("Client ID: ");
console.log(clientID);
/* OUTPUT 
Client ID:
Object {}
*/

As you can see, the main problem is that when I assign explodeClientID to a regular variable, it has value. But when I use setState to update, it still returns an empty object. This shouldn't be an issue at all since it's not an API call that I need to await.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83
ehmhrgelcighsawmlv
  • 309
  • 1
  • 3
  • 14
  • Does this answer your question? [Is there a synchronous alternative of setState() in Reactjs](https://stackoverflow.com/questions/42018342/is-there-a-synchronous-alternative-of-setstate-in-reactjs) – Jared Smith Oct 14 '20 at 03:23
  • @JaredSmith the post you linked changes value on a click, I want to change the value on component load. I also used useEffect for this but the value is still null. – ehmhrgelcighsawmlv Oct 14 '20 at 05:20
  • The problem is the same and the answer is the same. There's no synchronous version of `setState`, not in classes, not in hooks. It makes no sense: if you already have the value, then pass that as the initial value to `useState`, don't trigger a pointless re-render on mount. Why are you passing an empty object instead of explodeClientID? – Jared Smith Oct 14 '20 at 11:33

1 Answers1

0

can you try with this:

const [clientID, setClientID] = useState({});

// explodeClientID is an object
let explodeClientID = ClientIDFormatter(routeParams.QRData);
// I assign that variable to me clientID state:
setClientID(explodeClientID);

// I logged the variable:
console.log("Exploded Client ID:")
console.log(explodeClientID);
/* OUTPUT: 
Exploded Client ID:
Object {
  "BR_ID": 1,        
  "ClientChkID": 4,  
  "ClientID": 599920,
} */

React.useEfect(()=>{
console.log(clientID)
}, [clientID])