React
How to integrate it in React projects
First at all you need configure ShapeRQ for your project, you can do somthing like this:
import { createConfig } from 'shape-rq'
export function createApi() {
createConfig({
APIs: {
Cheese: {
baseUrl: "https://cheese-api.onrender.com",
auth: {
token: () => localStorage.getItem('cheesyToken'),
prefix: "Cheese"
}
}
},
debug: true,
lang: 'en',
})
}
and then
...
createApi()
...
The config is set once, on app start.
Make sure you call createApi()
before sending any requests.
âś… What's next?
Let's get some cheese...
...
const [cheeses, setCheeses] = useState<CheeseType[]>([]);
useEffect(() => {
const getCheeses = async () => {
const res = await httpGet<CheeseType>("cheese", "/cheeses");
if (res) setCheeses(res);
};
getCheeses();
}, []);
...
...
return(
<>
{
cheeses.map(cheese => (
<CheeseComponent cheese={cheese}/>
)
}
</>
)
What if I need requests more then one API?
You can. Just do that:
...
ExAPI: { baseUrl: "https://api.example.com/" }
...
And:
...
const getUser = async () => {
const res = await httpGet<userType>("ExAPI", "auth/user")
// error 401, and null 'cause we don't set auth method for ExAPI
if (res) setUser(res)
}
...
For fix it just add another token
...
ExApi: {
auth: {
token: () => localStorage.getItem("exapiToken"),
prefix: "Bearer",
}
}
...
❔How I can create new data?
Great queastion! The answer:
...
const [username, setUsername] = useState<string>("")
const [password, setPassword] = useState<string>("")
const onSubmitHandler = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
const body = {username, password}
const res = httpPost(
"ExAPI",
"auth/signup/",
{
body: body,
xsrf: false // Disable xsrf protect, there no need in it
}
)
if (res.ok) console.log(res)
}
...
...
return(
<form onSubmit={(e) => onSubmitHandler(e)}>
...
</form>
)
Last updated