next.js 如何在SWR中改变数据

wnavrhmk  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(160)

我有两个功能。第一个获取数据并返回所有引号、突变函数和加载布尔值。

// Fetcher and the baseUrl
export const baseURL = 'http://localhost:3000/api/';
export const fetcher = (arg: any, ...args: any) => fetch(arg, ...args).then(res => res.json());



//get completed quotes
export const getAllQuotesArray = () => {
    const { data: allQuotes, isLoading: allQuotesLoading, mutate: mutateAllQuotes } = 
    useSWR(`${baseURL}/get-quotes`, fetcher);

    return { allQuotes, allQuotesLoading, mutateAllQuotes };
}

第二个函数删除一条记录并返回剩余的对象数组(与API路由中相同)。

//get completed quotes
export const getCompletedQuotes = async () => {
    try {
        const response = await fetch(`${baseURL}get-completed-quotes`, {
            method: 'GET'
        });
        const data = await response.json();
        return data;
        
    } catch (error) {
        console.log('', error);        
    }
}


export const deleteFromCompletedQuotes = async (quoteId: string) => {
    try {
        await fetch(`${baseURL}delete-quote?id=${quoteId}`, {
            method: 'DELETE'
        });
        const allRemainingCompletedQuotes = await getCompletedQuotes();

        //re run the function
        getAllQuotesArray();

        //return an array of objects
        return allRemainingCompletedQuotes.completedQuotes;
        
    } catch (error) {
        console.log('', error);        
    }
}

如何重新验证deleteFromCompletedQuotes函数中的数据?我试过很多次变异...但这行不通。我的方法的原因是因为我有两个组件在我的网页,其中一个显示完整的报价和其他所有的报价。但是如果我删除一条记录,在第二个div中不会发生任何变化...

js5cn81o

js5cn81o1#

getAllQuotesArray()返回{ allQuotes, allQuotesLoading, mutateAllQuotes }。可以在deleteFromCompletedQuotes中使用mutateAllQuotes mutator
export const deleteFromCompletedQuotes = async(quoteId:string)=> { try { await fetch(${baseURL}delete-quote?id=${quoteId},{ method:"}); const allRemainingCompletedQuotes = await getCompletedQuotes();

//re run the function
    const {mutateAllQuotes}=getAllQuotesArray();
    // it's argument must be the data that you returned in the first place, which is all quotes
    // now you need to pass allRemainingQuptes
    mutateAllQuotes(allRemainingCompletedQuotes)

    //return an array of objects
    return allRemainingCompletedQuotes.completedQuotes;
    
} catch (error) {
    console.log('', error);        
}

}

相关问题