apinext.jsstrapiswr

fetching data form strapi with bearer token using SWR on next js


hi there im using strapi for cms and next js for frontend, and using swr and axios for data fething im trying to fetch data from strapi backend using bearer token , and here is my code

const address = `${process.env.NEXT_PUBLIC_API_URL}/products` 
const auth = `${process.env.NEXT_PUBLIC_API_TOKEN}`

const fetcher = async (url) => await axios.get(url).then((res)=> res.data)
const {data, error} = useSWR(address, auth, fetcher)

console.log(data) 

and when i console.log(data) it's always shown undefined , it's something wrong with my code ? it's any correct way to fetch data with bearer token?


Solution

  • i've found the answer thanks anyway

    const address = `${process.env.NEXT_PUBLIC_API_URL}/products?populate=*`;
      const auth = `${process.env.NEXT_PUBLIC_API_TOKEN}`;
      async function fetcher(url) {
        const response = await axios.get(url, {
          headers: {
            Authorization: `Bearer ${auth}`,
          },
        });
        return response.data.data;
      }
      const { data, error } = useSWR(address, fetcher);
      let loading = !data && !error;
      console.log(data);