In useEffect I call getPins which queries a DB for pins. I am then looping through the pins and and trying to decrease 'pinsRemaining' which is a state hook.
In state it shows that the hook decreases, but it's not working in the code. When I console log pinsRemaining from getPinnedLocations() its always the same number.
The interesting thing is that if I make 'pinsRemaining' a const varaible (not state hook) it does work to decrease the counter, but that creates other problems.
I'm not sure how to get this code to work. I've read about how state hooks are async here
useState set method not reflecting change immediately
I've tried just adding an empty useEffect hook like this but it doesn't work
useEffect(() => {}, [pinsRemaining])
Maybe I need to be doing something inside of this?
Here is my full code.
const [pinsRemaining, setPinsRemaining] = useState(5)
useEffect(() => {
if (isLoggedIn && user !== {}) {
APIService.getAccountById(
Number(id)
).then(_user => {
setUser(_user)
getPins(_user)
}).catch(err => {
console.log("error", err)
})
}
}, []);
const getPins = (_user) => {
APIService.getPinsForUser(_user.id).then(pins => {
pins.map(pin => {
pushPinnedLocation(pin.location_id, _user)
})
})
}
const pushPinnedLocation = (location, date, _user) => {
//decrementing in hook doesn't work here
setPinsRemaining((prevState)=> prevState - 1)
//but decrementing with var does
pins = pins - 1
console.log("state hook", pinsRemaining)
console.log("const var", pins)
setLocationDateMap(new Map(locationDateMap.set(location, date)))
if(pinsRemaining === 0){
getMatchesFromDB(_user)
}
}
const getMatchesFromDB = (_user) => {
let pinsArray = Array.from(locationDateMap)
pinsArray.map(obj => {
let location = obj[0]
let date = obj[1]
let locationDate = date + "-" + location
let dbMatches;
let params = {
location_date_id: locationDate,
user_id: _user.id,
seeking: _user.seeking
}
APIService.getMatchesByLocationDateId(params).then(data => {
dbMatches = data.map((match, i) => {
if(match.likes_recieved && match.likes_sent
&& match.likes_recieved.includes(_user.id + "")
&& match.likes_sent.includes(_user.id + "")){
match.connectedStatus = 3
}else if(match.likes_recieved && match.likes_recieved.includes(_user.id + "")){
match.connectedStatus = 2
}else if(match.likes_sent && match.likes_sent.includes(_user.id + "")){
match.connectedStatus = 1
}else{
match.connectedStatus = 0
}
match.name = match.user_name
return match
})
}).then(() => {
setMatches(matches => [...matches, ...dbMatches]);
})
})
}