gtry
gtry2y ago

useState not working as expected.

Hi, I am trying to use the useState method of crawler like below
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');
})
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
2 Replies
ondro_k
ondro_k2y ago
Hi, try if it works with an array instead of Set:
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');
})
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.
gtry
gtryOP2y ago
Thanks, in one of actors I saw it using a set.

Did you find this page helpful?