在NextJ中使用SWR和上下文API时未获取数据
我正在尝试查看使用SWR从API获得的数据,并将API中的货币设置为用户通过上下文API使用的任何内容,但我看不到任何数据。请有人帮忙。知道什么不对。
这是代码
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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
代码下面的工作(测试):
检查您的
const {crorment} = usecontext(cryptostate)
在您的情况下
fetcher
不需要,> fetcher
fetcher 变量是针对复杂情况进行的。PS而不是检查您的货币并使用
usecontext
挂钩,您可以将此变量直接发送到您的函数,以函数趋势(货币)
Code below works (tested):
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 asfunction Trending(currency)