Created
September 7, 2019 12:26
-
-
Save fernandoabolafio/747ff127a71acbb9aa4fe468a5aab8af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useMemo, useState, useCallback } from "react"; | |
import useQueryString from "./useQueryString"; | |
function useQueryStringWithIndexValue(key, initialIndex, values) { | |
const computedValues = useMemo(() => values.map(v => v.toLowerCase()), [ | |
values | |
]); | |
const [value, onSetValue] = useQueryString(key, values[initialIndex]); | |
const [index, setIndex] = useState(initialIndex); | |
const onSetIndex = useCallback( | |
index => { | |
const newValue = computedValues[index]; | |
onSetValue(newValue); | |
},a | |
[computedValues, onSetValue] | |
); | |
useEffect( | |
function onValueChange() { | |
const newIndex = computedValues.findIndex(v => v === value); | |
setIndex(newIndex >= 0 ? newIndex : initialIndex); | |
}, | |
[value, computedValues, initialIndex] | |
); | |
return [index, onSetIndex]; | |
} | |
export default useQueryStringWithIndexValue; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice work to async state to url. I try your useQueryString. It works fine. But i don't understand how to use the useQueryStringWithIndexValue.
Expect for your demo.