Vencovsky
Vencovsky

Reputation: 31625

How to make a function that replicates useState()[1] with typescript?

What I want to do:

I'm making a custom hook and I want to make a function that will be equivalent to useState()[1] which means, equivalent to the setState function of useState.

const setMyState = value => { ... }

And value can be either the value to update or a function that will receive the previous state and return the updated value.

But what type should I use for that?

Example and expectations of what I'm trying

The one example I'm trying to do is create the useLocalStorage hook in typescript.

Where is what I have done so far

// what should this type be?
type Foo = ???
type Bar = ???

function useLocalStorage<T>(key: string, initialValue: T): [T, Foo] {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  })

  // Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
  const setValue: Foo = (value: Bar) => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      // Save state
      setStoredValue(valueToStore);
      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      // A more advanced implementation would handle the error case
      console.log(error);
    }

  }

  return [storedValue, setValue];
}

export default useLocalStorage

What I have tried so far

I tried to put React.SetStateAction<T> which is what I need for the setValue

type SetStateAction<S> = S | ((prevState: S) => S);

But looks like it doesn't work and this gives me the error

function useLocalStorage<T>(key: string, initialValue: T): [T, React.SetStateAction<T>] {
    ...
    const setValue: React.SetStateAction<T> = (value: React.SetStateAction<T>) => { ... }
}

Type '(value: React.SetStateAction) => void' is not assignable to type 'SetStateAction'.
Type '(value: React.SetStateAction) => void' is not assignable to type '(prevState: T) => T'.
Type 'void' is not assignable to type 'T'.

But I really don't understand why, could someone explain what is wrong where?

Upvotes: 1

Views: 491

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

useState()[1] returns React.Dispatch<React.SetStateAction<T>> type. So I think you meant to implement like so:

type Foo<T> = React.Dispatch<React.SetStateAction<T>>;
type Bar<T> = React.SetStateAction<T>

Full Code:

function useLocalStorage<T>(key: string, initialValue: T): [T, Foo<T>] {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once

  const [storedValue, setStoredValue] = React.useState<T>(() => {
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  });

  // Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
  const setValue: Foo<T> = (value: Bar<T>) => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      // Save state
      setStoredValue(valueToStore);
      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      // A more advanced implementation would handle the error case
      console.log(error);
    }
  };

  return [storedValue, setValue];
}

Upvotes: 2

Related Questions