Promise {<pending>} Graphql, and strapi with nextjs - next.js

With GraphQL and nextjs, I'm trying to retrieve some data from strapi.
When I try to access these data from the other file and display them on the UI, I get this error Promise {} in console.log.
This is what i tried
sliderAdapter.js
import { fetchSlider } from "./apiClient";
export const sliderAdapter = async (data, locale, url) => {
const sl = await fetchSlider();
const deepDownSlides = sl.data?.slides?.data;
if (deepDownSlides.length > 0) {
const slider = deepDownSlides[0]?.attributes?.slider;
// console.log("slider", slider);
return slider;
}
// This code is working but not properly, just return the data into the console.
return "";
};
fetchSlider is the file where i put the query.
Next:
import { sliderAdapter } from "../../lib/sliderAdapter";
const Slider = (data) => {
const slide= sliderAdapter(data)
console.log("slide", slide)
If anyone knows or can find the issues, plz let me know :)

Your function is asynchronous so you have to retrieve the value once the promise is resolved
sliderAdapter(data).then(slide=>console.log(slide))

Related

Problem when trying to fetching data with websocket

I'm trying to fetch Binance real time data with node-binance-api package in my NextJS project, i have know that to let real time data render on my UI, i have to use websocket, at getServerSideProps() function, I dont know how to return the exactly the real time data and render it on BinanceData() function
I use Nextjs, node-binance-api and websocket, websocket is already connected.
Here is what I trying data
import React from 'react'
const Binance = require('node-binance-api')
import {io} from 'socket.io-client'
let socket = io();
const BinanceData = ({price}) => {
const socketInitializer = async () => {
await fetch('/api/socket')
socket = io()
socket.on('connect', () => {
console.log('connected')
})
}
socketInitializer();
return (
<div>
<h2>
{price}
</h2>
</div>
)
}
export default BinanceData
export async function getServerSideProps()
let sockets = io();
const apiKey = process.env.NEXT_PUBLIC_BINANCE_API_KEY;
const secretKey = process.env.NEXT_PUBLIC_BINANCE_SECRET_KEY;
const binance = new Binance().options({
APIKEY: apiKey,
APISECRET: secretKey
});
const price = binance.futuresMiniTickerStream('BTCUSDT', (data) =>{
console.log(data.close);
sockets.emit('send-price',data.close);
});
return {
props:{
price
}
}
}
I already get my real time data in console log with line console.log(data.close); and here is my result
enter image description here
I do not know how to return the correct value of "price" in order to get the correct value on
BinanceData() function and my real time data is appear correct on my UI
I'm very grateful with any advise and I will carefully trying on it.
Thanks for all of you help !

How to use `useRoute`/`useRouter` in a Pinia Store using Setup Store syntax in Vue3?

I've been trying to get my Pinia store up and running in Vue 3 and it all has been pretty effortless until I wanted to access some parameters in the url.
I have a store (simplified) like so:
import { defineStore } from 'pinia';
import { useRoute } from 'vue-router';
import { useLocalStorage } from '#vueuse/core';
export const useUserStore = defineStore('user', () => {
const route = useRoute();
const uuid = ref(
useLocalStorage('uuid', route.params.id)
)
return { uuid };
})
Unfortunately, the route remains undefined as if useRoute() is not triggered properly. I've seen that you can add plugins to add the router instance to the pinia store on initialisation, but there's no way I can find to access that this instance in a Setup Store.
Any help would be greatly appreciated
route is not defined when the pinia is initiated.
You need to wait a bit.
One way to do this is to call the function when the component is loaded.
export const useUserStore = defineStore('user', () => {
const route = useRoute();
const id = ref('');
const setId = () => {
id.value = route.params.id as string; // don't need as string if you don't use TypeScript
};
return { id, setId };
});
<script setup lang="ts">
import { useUserStore } from '../stores/user';
const user = useUserStore();
user.setId(); // call the function from pinia, route.params works just fine
</script>
Link Demo

Scrape supporters name from buymeacoffee website

I am trying to scrape supporters names from this https://www.buymeacoffee.com/singtaousa website.
Currently, I am able to get the total number of supporters using axios and cheerio modules. The problem is I can't figure out how to get the supporters name.
I also tried to search with span, not a single supporters name comes out. Not sure whether my code is wrong or the names are impossible to be retrieved.
Here is my code:
import cheerio from 'cheerio'
import axios from 'axios'
export default async function handler(req, res) {
const { data } = await axios.get('https://www.buymeacoffee.com/singtaousa') // example
const $ = cheerio.load(data)
const count = $('.text-fs-16.av-medium.clr-grey.xs-text-fs-14.mg-t-8').text()
const supporters = []
// to be change
$('span').each((i, element) => {
const name = $(element).text()
supporters.push(name)
})
res.status(200).json({ count, supporters })
}
The names are added by JavaScript, so you need something like puppeteer or any other headless browser runner to get full-fledged script-based page content. Here is an example for your case using puppeteer:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
try {
const [page] = await browser.pages();
await page.goto('https://www.buymeacoffee.com/singtaousa');
const namesMinimum = 20;
const nameSelector = 'div.supp-wrapper span.av-heavy';
const moreSelector = 'button#load-more-recent';
await page.waitForSelector(moreSelector);
while (await page.$$eval(nameSelector, names => names.length) < namesMinimum) {
await Promise.all([
page.click(moreSelector),
page.waitForResponse(
response => response.url().includes('www.buymeacoffee.com')
),
]);
}
const data = await page.evaluate(() => {
const names = Array.from(
document.querySelectorAll('div.supp-wrapper span.av-heavy'),
span => span.innerText,
);
return names;
});
console.log(data);
} catch (err) { console.error(err); } finally { await browser.close(); }
You will need to load all supporters with this method from console or manually because you don't have all of them loaded once:
await document.getElementById("load-more-recent").click();
The request for loading supporters is traceable via network tab of developer tools. After loading all, you can copy a list of names from output of code below. You can change concatenation for your output, or ignore null values, but basically that's working:
var supporters = $("div.supp-wrapper");
var list = [];
for(var i = 0; i < supporters.length; i++){
list.push(supporters[i].querySelectorAll("span.av-heavy")[0].textContent.trim(" "));
}
console.log(list);
this script will result:
(10) ['Amy', 'Wong', 'Someone', 'Someone', 'Someone', 'Emily', 'KWONG Wai Oi Anna', 'Simon wong', 'Elaine Liu', 'Someone']
To get all of the supporters name you need to load all with the click script above. Otherwise you can checkout network tab to use API request.

TypeError: (0 , _reduxjs_toolkit__WEBPACK_IMPORTED_MODULE_0__.createAsyncThunk) is not a function

Suddenly had this error after (it seems..) trying to deploy my client to Vercel.
I'm using NextJS and I'm fetching data server side with getStaticProps.
Tried reinstalling toolkit but the problem persist.
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
What could possibly be wrong ?
if it matters, here's how I use createAsyncThunk in my slice :
export const countProducts = createAsyncThunk(
"products/countProducts",
async (undefined, { getState }) => {
const { filterBy } = getState().product;
const url = `${process.env.STRAPI_URL}/products/count?categories.name_contains=${filterBy}`;
const { data } = await api.get(url);
return data;
}
);
Any help would be GREATLY appreciated.
Fixed it, I just somehow had an older version of toolkit installed (v1.2.x).

Method "Astronomy/execute" not found in meteor

Okay, I build Game DB schema using astronomy package in meteor.
Then I try to add method to it by extending it in server. (server/gamehandle.js)
import {Game} from '../imports/db/game'
import {DDP} from 'meteor/ddp-client'
Game.extend({
meteorMethods: {
AddNewGame(judul){
const invocation = DDP._CurrentInvocation.get()
this.namaGame = judul
this.creator = invocation.userId
this.createdAt = new Date()
return this.save()
}
}
})
But when I try to run the method in app client using callMethod it throw an error that astronomy/execute not found 404.
This the component using it
import {Game} from '../../../db/game'
export function NewGameList(props){
const { isOpen, onOpen, onClose } = useDisclosure()
const [judul, setJudul] = useState('')
const [hasil, setHasil] = useState(null)
const judulChange = (e) => setJudul(e.target.value)
const AddGame = new Game()
const handleSubmit = (e) => {
e.preventDefault()
AddGame.callMethod('AddNewGame', judul, (err, result) => {
result ? setHasil(result) : setHasil(err.message)
console.log(err)
})
}
...
So enlight me, what thing I do wrong?
Finally found the solution from meteor slack.
Just need to imports my db file to main js file in server.

Resources