keajs / kea-router

Router for Kea
MIT License
6 stars 5 forks source link

Easier sync of values and the URL #5

Open mariusandra opened 4 years ago

mariusandra commented 4 years ago

To simplify cases like this, it would be nice to have a better way to convert the values to an URL, no matter which action was triggered.

This code:


const buildURL = (selectedDateURLparam: string, sessionRecordingId: SessionRecordingId | null): [string, Params] => {
    const today = moment().startOf('day').format('YYYY-MM-DD')
    const params: Params = {}

    const { properties } = router.values.searchParams // eslint-disable-line
    if (selectedDateURLparam !== today) {
        params.date = selectedDateURLparam
    }
    if (properties) {
        params.properties = properties
    }
    if (sessionRecordingId) {
        params.sessionRecordingId = sessionRecordingId
    }

    return [router.values.location.pathname, params]
}

kea({
    ...
    actionToUrl: ({ values }) => ({
        setFilters: () => buildURL(values.selectedDateURLparam, values.sessionRecordingId),
        loadSessionPlayer: () => buildURL(values.selectedDateURLparam, values.sessionRecordingId),
        closeSessionPlayer: () => buildURL(values.selectedDateURLparam, values.sessionRecordingId),
    })
})

... could become:

kea({
    ...
    valuesToUrl: ({ values }) => {
        const { selectedDateURLparam, sessionRecordingId } = values
        const today = moment().startOf('day').format('YYYY-MM-DD')
        const params: Params = {}

        const { properties } = router.values.searchParams // eslint-disable-line
        if (selectedDateURLparam !== today) {
            params.date = selectedDateURLparam
        }
        if (properties) {
            params.properties = properties
        }
        if (sessionRecordingId) {
            params.sessionRecordingId = sessionRecordingId
        }

        return [router.values.location.pathname, params]
    }
})

or something like that.

Some questions with this:

  1. Should it be
    • valuesToUrl: ({ values }) => { } or
    • valuesToUrl: (values) => { } aka valuesToUrl: ({ selectedDateURLparam, sessionRecordingId }) => { }
  2. When to run the comparison between the current URL and the required URL? On every action? On only actions in this logic?
  3. Can you opt out by returning null?