Hey guys, I’m having a hard time figuring this one out. I am switching certain CRUD functionality that I used to provide with a token, but now I am using SWR. Here are the docs:
I’m working on refactoring the POST request that I passed with the token like I have here:
const postArt = async (title, year, medium, url, price) => {
const artBody = {
title: title,
year: year,
medium: medium,
poster: url,
price: price
}
const response = await fetch(`${API}/chizetteart`, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": "application/JSON",
"Content-Type": "application/json",
"token": token
},
body: JSON.stringify(artBody)
})
if (response.status !== 200) {
alert(`Unable to create this masterpiece!`)
} else {
alert(`Art Created!`)
}
setArtList([artBody, ...artList])
}
But now, I have SWR calling the data and caching it in a higher level context:
import React, { createContext } from "react"
import useSWR from 'swr'
// Node API
// const API = process.env.REACT_APP_API
const API = 'http://localhost:3000'
export const ArtListContext = createContext()
export function ArtListProvider(props) {
const fetcher = url => fetch(url).then(r => r.json())
const { data } = useSWR(`${API}/chizetteart`, fetcher)
return (
<ArtListContext.Provider
value={{ data }}
>
{props.children}
</ArtListContext.Provider>
)
}
And I am calling that data in the component that I want the admin to make a POST request with the token as a header. I am looking at the multiple arguments array but not quite sure how to get it done here:
Lines 47 - 66 — the logic to take from the form state and put into an object,
93 - 102 — the submit event listener, where I am trying to use the SWR hook mutate().
Any help would be much appreciated.