Skip to content

Instantly share code, notes, and snippets.

@fernandoabolafio
Created September 7, 2019 12:26
Show Gist options
  • Save fernandoabolafio/747ff127a71acbb9aa4fe468a5aab8af to your computer and use it in GitHub Desktop.
Save fernandoabolafio/747ff127a71acbb9aa4fe468a5aab8af to your computer and use it in GitHub Desktop.
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;
@DarkPage
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment