question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Use existing Hooks to populate state typescript how to

See original GitHub issue

I have hooks that provide data already, since hooks can be used only inside another hook or inside a react component, I’ve created a custom hook to make use of the existing hooks and get data, that data, in turn, can be used to populate state and the state is returned from that custom hook.

I’m using state slicing and creating a store from the slice returned from the custom hook.

The state is getting updated but I don’t see any changes in UI. I don’t know where I’m doing wrong or is there an existing solution to achieve this ? Please help

I’ve put together a contrived example on code sandbox here

https://codesandbox.io/s/youthful-tdd-05z8c?file=/src/useStoreHook.ts

you can check the console for all the logs of updates

import create, {
  GetState,
  SetState,
  StateCreator,
  StoreApi,
  UseStore
} from "zustand";
import { devtools } from "zustand/middleware";
import { v4 as uuidv4 } from "uuid";
import { useEffect, useState } from "react";

export type TTodo = {
  userId: number;
  id: number | string;
  completed: boolean;
  title: string;
};

export type TState = {
  todos: TTodo[];
  addTodo: () => void;
  removeTodo: ({ id }: { id: string | number }) => void;
};

const fetchTodos = async () => {
  const todos = await (
    await fetch("https://jsonplaceholder.typicode.com/users/1/todos")
  ).json();
  return todos;
};

// Existing custom hook which can be used to populate store data
const useTodo = () => {
  const [todos, setTodos] = useState<any[]>([]);

  useEffect(() => {
    async function fetchData() {
      const data = await fetchTodos();
      setTodos(data);
    }
    fetchData();
  }, []);

  return todos;
};

const useCreateBaseSlice = () => {
  const todos = useTodo();

  const slice: StateCreator<TState> = (set, get) => ({
    todos: Array.isArray(todos) ? todos : [],

    addTodo() {
      const item = {
        id: uuidv4(),
        userId: Math.floor(Math.random() * (1000 - 1) + 1),
        title: "Todo Text",
        completed: false
      };
      console.log(`adding todo ${JSON.stringify(item, null, 2)}`);
      set((state) => {
        state.todos = [item, ...state.todos];
        console.log(get().todos);
      });
    },

    removeTodo({ id }) {
      set((state) => {
        const excludedTodos = state.todos.filter((todo) => todo.id !== id);
        state.todos = [...excludedTodos];
      });
    }
  });

  return slice;
};

const useCreateStore = (): UseStore<TState> => {
  const baseSlice = useCreateBaseSlice();

  return create<TState>(
    devtools((set, get, api) => ({
      ...baseSlice(
        set as SetState<TState>,
        get as GetState<TState>,
        api as StoreApi<TState>
      )
    }))
  );
};

export default useCreateStore;

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
anvercommented, Oct 25, 2021

I didn’t understand this part, it’s all foreign to me but thanks for your time, may be i’ll figure that out later sometime.

Sorry for confusion. It simply means “don’t use hooks”.

But, that doesn’t answer to the question of this issue, so here’s the solution for you. https://codesandbox.io/s/trusting-feynman-mnkz3?file=/src/useStoreHook.ts

Awesome, thanks, one last thing, you need to wire up the handleRemove action to the remove icon in the codesandbox 😃

Nice work, I really appreciate it…

0reactions
anvercommented, Oct 25, 2021

This is a cleaner sandbox if someone needs to refer.

https://codesandbox.io/s/working-async-fetch-zustand-fo9rn?file=/src/useStoreHook.ts

Thanks again @dai-shi

Read more comments on GitHub >

github_iconTop Results From Across the Web

The React TypeScript Cheatsheet – How To Set Up Types on ...
To set types on the useState hook, you need to pass into <> the type of the state. You can also use a...
Read more >
How to Create a Reusable Custom Hook with React and ...
Using useFetch Custom hook · Import useFetch · Create an IAlbum interface to represent the response type · Destructure the states from the...
Read more >
Easy typed state in React with hooks and Typescript - Medium
npx create-react-app type-safe-state-ftw --typescript ... Now whenever we need to use a hook from our hooks.ts file they will be able to ...
Read more >
React & TypeScript: how to type hooks (a complete guide)
username} onChange={(event) => dispatch({ type: 'username', payload: event.target.value }) } /> <input type="email" value={state.email} onChange ...
Read more >
How to create a custom React hook to fetch an API (using ...
A hook is a javascript or typescript function that can include other hooks. Its name starts with « use », and this function...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found