I am trying to update the value of a state from another function.
I have declared them like so:
const App () => {
const [positionAX, setPositionAX] = useState(100)
const [positionAY, setPositionAY] = useState(100)
}
outside of App I have another function:
const setPosition = () => {
setPositionAX(200);
setPositionAY(200);
}
When I call setPosition() I get the error:
Cant find Variable: setPositionAX
Cant find Variable: setPositionAY
I tried to move const [positionAX, setPositionAX] = useState(100) to the top of my file but then I got the error:
Invalid hook call. Hooks can only be called inside of the body of a function.
How do I update that variable from other functions?
Edit 1 for @t-j-crowder
I can't seem to get this to work, I am not sure what I am doing wrong
Here is a live snack example of the code you gave me: https://snack.expo.io/Cd!hwDQ0m
If I add an alert:
alert("pressed")
Into the handleClick function, that works so for some reason it is just not working with the setPositionA([200, 200]).
Also as an additional note: In my app example, there are two functions and the functionality of setting the state, and the functionality of displaying the state are separated which is why I am getting the issue I meant to present in my initial Stack overflow post.
Here is a snack of that example of what I am trying to achieve:
https://snack.expo.io/6TUAkpCZM
I am using the 'positionX' and 'positionY' as vars to define the Top and Left position of an element which are rendered out, however, the actual setting of the positionX and positionY variable is done in another function
I am a junior developer so I really want to thank you for all your help with this and also apologise if this is super nooby.
Edit 2 for: Muhammad Numan
I tried your way and I just can't seem to get it to work. I think there is some confusion as to what I want to achieve and where I want to achieve it. That is probably my fault as I am a noobie developer so please forgive me. I didn't want to just post all my code as I think its frowned upon for people to just code dump and be like "fix this" - however, for this situation its probably best haha.
Here is a full snack of my code: https://snack.expo.io/uk8yb5xys
What I want is this:
The user is instructed to draw a line from the word "start" to the word "end". If the line is drawn and the start point and endpoint of the users line match the given path, they are then presented with another line to draw and the position of "start" and "end" will move so the user knows where to draw.
There is a comment line:
// HERE IS WHERE I NEED TO UPDATE THE VALUES FOR START AND END
This is where I need the word "start" and the word "end" to move to their new positions.
At the moment, when you draw a complete line and remove your finger from the screen - nothing happens. However, when you put your finger down the start and end do move. I need them to move when the user lifts up their finger.
I appreciate your time with this so thank you.
