Juliette
Juliette

Reputation: 4429

handling promise for react render

I have the code below:

async function determineCounters() { 
 #do something
}



determineCounters()
.then(response => {
  let var2 = response[0];
  let var3 = response[1];
});

const [activityCounter, setActivityCounter] = React.useState(var2);
const [awardCounter, setAwardCounter] = React.useState(var3);

return(
   #uses activityCounter and awardCounter
)

When I run this code, activityCounter and awardCounter are not populated with the correct var2 and var3 values which screws up what is shown in the return. How can I delay the counter and the return to wait for var2 and var3 to finish?

Upvotes: 0

Views: 39

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Wrap the then in useEffect

const [activityCounter, setActivityCounter] = React.useState(null);
const [awardCounter, setAwardCounter] = React.useState(null);

React.useEffect(() => {
  determineCounters().then((response) => {
    let var2 = response[0];
    let var3 = response[1];
    setActivityCounter(var2);
    setAwardCounter(var3);
  });
}, []);

Upvotes: 0

PixAff
PixAff

Reputation: 329

You need to declare your state variables on top of your component and the set them like so:

determineCounters()
.then(response => {
  setActivityCounter(response[0])
  setAwardCounter(response[1])
});

When you declare them you give them an initial state:

const [activityCounter, setActivityCounter] = React.useState(null); // or whatever you need as initial state

Upvotes: 1

Related Questions