Skip to content

Instantly share code, notes, and snippets.

@sirius0486
Created January 23, 2025 09:14
Show Gist options
  • Save sirius0486/3fd6fbe69b299409e359591e16aae912 to your computer and use it in GitHub Desktop.
Save sirius0486/3fd6fbe69b299409e359591e16aae912 to your computer and use it in GitHub Desktop.
swr + zustand
// store/useIssueStore.ts
import create from 'zustand';
interface IssueStore {
issueId: number | null;
setIssueId: (issueId: number) => void;
}
const useIssueStore = create<IssueStore>((set) => ({
issueId: null,
setIssueId: (issueId) => set({ issueId }),
}));
export default useIssueStore;
// hooks/useIssue.ts
import useSWR from 'swr';
import { getAccessToken } from '../utils/authUtils';
import useIssueStore from '../store/useIssueStore';
interface IssueData {
issue_title: string;
description: string;
issue_id?: number;
}
interface IssueResponse {
issue_id: number;
// 其他字段
}
const fetcher = async <T>(url: string, options: { body: string; token: string; headers?: Record<string, string> }): Promise<T> => {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${options.token}`,
...options.headers,
},
body: options.body,
});
return response.json();
};
export function useIssue(issueData: IssueData, reviewAgain = false) {
const { issueId, setIssueId } = useIssueStore();
const body = reviewAgain
? { ...issueData, issue_id: issueId }
: issueData;
const { data, error, mutate } = useSWR<IssueResponse>(
['/api/issues', body],
([url, body]) => {
const token = getAccessToken();
if (!token) {
throw new Error('Access token is missing');
}
return fetcher<IssueResponse>(url, { body: JSON.stringify(body), token });
}
);
if (data?.issue_id && !reviewAgain) {
setIssueId(data.issue_id);
}
return {
data,
error,
isLoading: !data && !error,
mutate,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment