React

How to integrate it in React projects

First at all you need configure ShapeRQ for your project, you can do somthing like this:

loadConfig.ts
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

main.tsx
...
createApi()
...

The config is set once, on app start.


âś… What's next?

Let's get some cheese...

app.tsx
...
    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:

loadConfig.ts
...
ExAPI: { baseUrl: "https://api.example.com/" }
...

And:

app.tsx
...
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

loadConfig.ts
...
  ExApi: {
    auth: {
      token: () => localStorage.getItem("exapiToken"),
      prefix: "Bearer",
    }
  }
...

❔How I can create new data?

Great queastion! The answer:

RegPage.tsx
...
    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>
)

More about requests there

Last updated