Unable to retrieve data when utilizing SWR and Context API in Next.js

I'm currently working on fetching data from an API using SWR and dynamically setting the currency based on user preferences through context API. However, I'm facing issues as I am unable to view any data. Can someone please provide assistance or insights into where I might be going wrong?

Below is the code snippet:

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;

Answer №1

Working code snippet:

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;

Make sure to review your

const {currency } = useContext(CryptoState)

In this scenario, the fetcher variable may not be necessary for simpler cases.

Note: Instead of checking currency and utilizing the useContext hook, consider passing the variable directly to your function as function Trending(currency)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring information from an external JavaScript file to a Vue component

I am currently facing an issue with passing data from an external file called data.js to the component for its usage. The error I'm encountering states that the data is not defined. Below is the content of my data.js file: const data = [ { cha ...

Using the -g flag in Node.js consistently results in error messages

Whenever I attempt to install something globally with node, I encounter a series of errors. Interestingly, when I tried it in Powershell, no errors were thrown, but I suspect this is due to the fact that I was using Powershell instead of the official Node ...

Differentiating between swipe and click actions within Angular applications

Utilizing ng-click to display item details in a list while also implementing a jQuery mobile swipe event on the list item to reveal a delete button when swiped left has presented an issue. The problem arises when swiping triggers both the swipe event and a ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

Fetching data dynamically using ajax as you scroll

Currently, I am using the jQuery Tools Plugin to create an image slider. However, I am facing a challenge with loading a large number of images all at once. Since the slider is coded in JavaScript, I am not sure how to control the scroll position. I would ...

Express does not handle get requests to .html files

const express = require('express'); const app = express(); const port = 3000; const bodyPar=require('body-parser'); const session = require('express-session'); const path=require('path'); var user=["Jared","Bill","Ja ...

angular express cycle without end

I'm experiencing an issue with my express/angular app where the index page is causing an infinite loop. Here's how I have set up my app: app.configure(function() { // setting up our express application app.use(express.logger('dev& ...

JavaScript Regex: Removing all characters that are not numbers

There have been several inquiries about this particular question, such as this one on Stack Overflow. Despite my efforts to replicate the solution and research regex, I can't seem to get it to work: $("#button").click(function () { new_number = $ ...

Dispatch prop within useEffect

App.js -> <Lobbies inGame={inGame} setLobby={setLobby} userName={userName} userKey={userKey}/> Lobbies.js -> import React, { useState, useEffect } from 'react'; import firebase from 'firebase'; const Lobby = ({userKey, ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

Text that doesn't appear overwhelming in a Framer Motion text reveal animation

As a newcomer to Framer Motion, I recently attempted to create a Stagger Text effect and a Text Reveal Animation for my portfolio based on various articles. However, despite trying multiple examples, I have encountered an issue where the animation occurs s ...

Tips to prevent redirection in a JavaScript function

When a user clicks on a specific link, the HideN function is triggered. Here's an example: <a href="<?php echo $dn5['link']; ?>" onclick="HideN('<?php echo $dn5['id'];?>','<?php echo $dn5['fro ...

The journey of data starting from a PHP file, moving through JavaScript, and circling back to PHP

I've encountered an interesting challenge with my PHP file and Wordpress shortcode. It all starts when the shortcode is embedded in a webpage, triggering a php function from within the file. This function executes an SQL query to extract data, then s ...

Calculating the sha1 hash of large files using JavaScript in the browser without causing excessive memory usage

Is there a method to calculate the hash of large files in JavaScript without needing to load the entire file in a FileReader? Specifically, I'm interested in finding out if it's possible to stream a file and calculate its sha1 hash in JavaScript. ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

How can I make rows appear dynamically when the user clicks a button?

I am trying to add rows dynamically when the user clicks on a button. I have created a script for this purpose, but unfortunately, it is not working as expected. Can someone please assist me with fixing it? <script> var i; i = 2; function AddR ...

Proper method for managing errors in getServerSideProps within Next.js

I am currently facing an issue with handling errors that are being caught in getServerSideProps. Everything works smoothly until I introduce other hooks like useEffect. The problem arises when using the useEffect hook, as it triggers the following error - ...

Is it possible to use function declaration and function expression interchangeably?

As I dive into learning about functions in Javascript, one thing that's causing confusion for me is the difference between function declaration and function expression. For example, if we take a look at this code snippet: function callFunction(fn) { ...

Facing a challenge in configuring MongoDB automatic data expiration based on specific time zones

I am currently facing an issue with clearing data in MongoDB at the start of each day. For example, on July 15, 2020 at 00:00:00, data is deleted from the database based on a specific time. I am having trouble properly assigning the expiresAt attribute in ...

What steps can I take to help EventListener locate a specific class if it is experiencing difficulty?

In the process of creating a responsive navigation bar, everything seems to be functioning correctly except for a small javascript error that arises in my sub menu when clicking. Despite thoroughly checking through my index, script, and style files, I am ...