Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@DarkPage DarkPage commented Nov 18, 2020

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