0
votes

I have an array of countries received from Apollo backend without an ID field.

export const QUERY_GET_DELIVERY_COUNTRIES = gql`
    query getDeliveryCountries {
        deliveryCountries {
            order
            name
            daysToDelivery
            zoneId
            iso
            customsInfo
        }
    }
`

Schema of these objects:

{
    customsInfo: null
    daysToDelivery: 6
    iso: "UA"
    name: "Ukraine"
    order: 70
    zoneId: 8
    __typename: "DeliveryCountry"
}

In nested components I read these objects from client.readQuery. What I want is to insert it to localStorage, read it initially and write this data to Apollo Client Cache.

What I've already tried to do:

useEffect(() => {
    const deliveryCountries = JSON.parse(localStorage.getItem('deliveryCountries') || '[]')
    if(!deliveryCountries || !deliveryCountries.length) {
        getCountriesLazy()
    } else {
        deliveryCountries.map((c: DeliveryCountry) => {
            client.writeQuery({
                query: QUERY_GET_DELIVERY_COUNTRIES,
                data: {
                    deliveryCountries: {
                        __typename: "DeliveryCountry",
                        order: c.order,
                        name: c.name,
                        daysToDelivery: c.daysToDelivery,
                        zoneId: c.zoneId,
                        iso: c.iso,
                        customsInfo: c.customsInfo
                    }
                }
            })
        })
    }
}, [])

But after execution the code above I have only one object in countries cache. How to write all objects without having an explicit ID, how can I do it? Or maybe I'm doing something wrong?

1

1 Answers

0
votes

Lol. I just had to put the array into necessary field without iterating. writeQuery replaces all the data and not add any "to the end".

client.writeQuery({
    query: QUERY_GET_DELIVERY_COUNTRIES,
    data: {
        deliveryCountries: deliveryCountries
    }
})