React: Sequential functions, only second one updating state?

React: Sequential functions, only second one updating state?
0

#1

Hi Everyone,

I am stuck on something in a React app I am making. I am calling two functions that each “add” to the same string in state. I call them one after the other, but it seems only the most recently called one is acting as intended. Here are the details:

I have functions name enemyMove and playerAttack. They are very similar to each other. They both create a copy of combatLog from state, add some string text to it, and then set state.

I am calling the functions one after the other in the handleClick method. In the playerAttack function I console.log the combatLog from state. I do not console.log the combatLog in the enemyMove function.

In my render method I have a component called MoveAnimation which I pass a prop called log. This is the combatLog from state.

In the MoveAnimaton component I render the combatLog (passed as the prop “log”) to a text area.

When I click the Attack button I want it to show in the text area something like:

Player hits Enemy for x damage.
Enemy hits Player for x damage.

Instead, only the “Enemy hits” message is appearing, and weird things happen in the console.log from my playerAttack function:

The above picture was from me clicking the Attack button twice. On my first click the console it logs “Player hits Enemy for 1” twice, but shows “Enemy hits player for 2” on the text area. Any subsequent clicks add “Enemy hits” messages to the text area as well as the console log. The rest of the function like the math they do on the hp works properly. What the heck is going on here?

Any help would be appreciated!


#2

Might be useful.

Please, type or paste code instead of showing screenshots. It helps people trying to help :smiley:


#3

Thank you, it helped a lot! I will post code next time. sorry for the inconvenience.