Use existing Hooks to populate state typescript how to
See original GitHub issueI 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:
- Created 2 years ago
- Comments:6 (2 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
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…
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