'not getting data when using SWR and context API in Nextjs

am trying to see the data am that am get from an API using SWR and also setting the currency in the API to what ever the user is using through context API but i can't see any data. please can someone help out. to know what am not doing right.

here is the code

import React from 'react'
import useSWR from "swr";
import {CryptoState} from "../context/cryptoContext"
import { useContext } from "react";


function Trending() {

  const {currency } = useContext(CryptoState)

  const address = `https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&order=gecko_desc&per_page=10&page=1&sparkline=false&price_change_percentage=24h`;
  const fetcher = async (url) => await axios.get(url).then((res) => res.data);
  const { data, error } = useSWR(address, fetcher);

  if (error) <p>Loading failed...</p>;
  if (!data) <h1>Loading...</h1>;

  return (
    <div>
      {data && console.log(data)}
    </div>
  )
}

export default Trending;


Solution 1:[1]

Code below works (tested):

import React from 'react'
import useSWR from "swr";


function Trending() {


  const address = `https://api.coingecko.com/api/v3/coins/markets?vs_currency=USD&order=gecko_desc&per_page=10&page=1&sparkline=false&price_change_percentage=24h`;
  const { data, error } = useSWR(address);

  if (error) <p>Loading failed...</p>;
  if (!data) <h1>Loading...</h1>;
  return (
    <div>
      <pre>
        <code>
          {JSON.stringify(data, null, 2)}
        </code>
      </pre>
    </div>
  )
}

export default Trending;

Check your const {currency } = useContext(CryptoState)

In your case fetcher is not needed, fetcher variable is made for complex cases.

P.S. Instead of checking your currency and using useContext hook you can send this variable to your function directly as function Trending(currency)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1