Apify Discord Mirror

Updated 5 months ago

useState not working as expected.

At a glance

A community member is trying to use the useState method of a crawler, but is encountering an issue where state.id.has is not a function. Another community member suggests using an array instead of a Set, as Set is not serializable and may cause issues when the state is serialized, stored, and deserialized. The original poster acknowledges seeing the use of a Set in one of the actors, but there is no explicitly marked answer to the issue.

Hi, I am trying to use the useState method of crawler like below

Plain Text
const mystate = {
  id: new Set()
}

router.addHandler('ABC', async ({ request, crawler, sendRequest, response, body }) => {
    const state = await crawler.useState(mystate);

// now when I try to access the add/has id, I get something like state.id.has is not a function
state.id.has('myid123');
})


I am not sure how useState is supposed to work. can someone shed some light on it.
Thanks
o
g
2 comments
Hi, try if it works with an array instead of Set:
Plain Text
const mystate = {
  id: []
}

router.addHandler('ABC', async ({ request, crawler, sendRequest, response, body }) => {
    const state = await crawler.useState(mystate);

// now when I try to access the add/has id, I get something like state.id.has is not a function
state.id.includes('myid123');
})


Set is not serializable so when the state is serialized -> stored -> loaded -> deserialized then state.id becomes an empty object {}, hence state.id.has is not a function.
Thanks, in one of actors I saw it using a set.
Add a reply
Sign up and join the conversation on Discord