React query failing to transfer props to API

I am facing an issue while using react query to make an api call. I am unable to pass the props to the api url even though they are being logged successfully in the console.

//useData.js
import { useQuery } from "@tanstack/react-query";
import Error from "./Components/Error";
const myBaseUrl =
  "http://api.weatherapi.com/v1/forecast.json?key=59e580ae2ccf422c9fd551122xxxx";
const myFetchFunction = async (key, latitude, longitude) => {
  console.log(latitude); //value gets consoled
  try {
    const res = await fetch(
      `${myBaseUrl}&q=${latitude},${longitude}&aqi=yes&days=7`
    );
    const data = await res.json();
    return data;
  } catch (err) {
    console.log(err);
    return <Error />;
  }
};
export const UseData = (key, latitude, longitude) => {
  const { isLoading, isError, data } = useQuery(
    ["myData", latitude, longitude],
    (key) => {
      myFetchFunction(key, latitude, longitude);
    },
    {
      cacheTime: 3600000,
    }
  );
  return { isLoading, isError, data };
};


//mainScreen.js
  //calling the custom hook 
  const { data, isLoading, isError } = UseData("myData", 34.16, 23.14);

Any insights on what could be going wrong here?

Answer â„–1

Don't forget to include the return statement in the fetching function

    (item) => {
      fetchData(item, lat, long);
    },

The correct way is:

    (item) => {
      return fetchData(item, lat, long);
    },

Answer â„–2

One issue I encountered was mistakenly passing the key as a parameter while still including it in the function call:

export const fetchData = (key, latitude, longitude) => {
  const { isLoading, isError, data } = useQuery(
    [key, latitude, longitude],                      //replaced myData with key
    () => customFunction(key, latitude, longitude),
    {
      cacheTime: 3600000,
    }
  );
  return { isLoading, isError, data };
};

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

Revamp local route variables in Express.js without the need for a page refresh

Currently, I am working on a project using node.js along with the express.js framework and EJS for template handling. Below is my routing code: app.get('/',function(req,res) { res.render('index', { matches: [], status_messag ...

Content changing programmatically does not reset the scrollHeight

As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the ...

"Implementing a Django feature to open modal windows when clicking on individual links

I have a project that involves showcasing multiple Buildings on the buildings.html page, each displayed using a single image (big_image). My aim is to implement a modal feature where users can view additional images of the building when they click on it. ...

Is there a way to update a .json value using commands in Discord?

As a beginner in coding, I have successfully created a Discord bot using Node.js that has the ability to modify the entire config.json file, start and stop the bot, and create instances. However, I am currently facing a challenge where I need to update a s ...

"How to Integrate External Stylesheets in Puppeteer for Enhanced Web Design

My puppeter Js code is not retrieving all external stylesheets, even though I need them for further processing. Here's what I have so far: try { const browser = await puppeteer.launch(); const page = await browser.newPage(); page.on(&apo ...

Execute JavaScript AJAX Request On Page Load

I am facing an issue with creating an onload event in which an AJAX function needs to be called and passed a value. The challenge lies in the fact that I have both my header and footer split into sections via PHP, therefore I cannot place it on the body ta ...

CSS injection not working in Chrome extension content script

I'm attempting to add a CSS file to the PayPal homepage, but I'm encountering issues with it not working properly. Here is the manifest file I am using: { "manifest_version": 2, "name": "Paypal Addon", "version": "1.0", "descript ...

What is the best way to stop a UL element from inheriting the height properties of a drop down menu?

My sticky navigation bar is almost finished in terms of appearance and functionality. However, I encountered an issue when adding a drop-down menu within the links – it creates an invisible field that hides nearby text. Upon investigation, I found that t ...

Creating an array from CSV in Next.js API using Postman

I am looking to extract information from a CSV file sent through Next.js API, as shown in the image below However, I am unsure of how to approach reading this CSV file. Despite using the code snippet below, I am unable to successfully read the file. expo ...

Calculating Time Difference in JavaScript Without Utilizing moment.js Library

I have two timestamps that I need to calculate the difference for. var startTimestamp = 1488021704531; var endTimestamp = 1488022516572; I am looking to find the time difference between these two timestamps in hours and minutes using JavaScript, without ...

Is there a way to implement a targeted hover effect in Vue Js?

I'd like to create a hover button that only affects the nested elements inside it. Right now, when I hover over one button, all the nested elements inside its sibling buttons get styled. Any ideas on how to fix this? <div id="app"> <butto ...

Angular JS presents an exciting feature called Multiple Filters, which allows

I have a data representation application that displays information in table format with columns id, name, price, quantity The data is presented using ng-repeat. You can view it on this Plunker <body ng-controller="myController"> <h1>Data< ...

Step by step guide on showcasing live server information obtained from the user-end through AJAX technique in a Javascript Pie Chart, within an ASP.NET html template

I have successfully managed to transfer data from the Client Side (C# Back End) to the Server Side (Javascript HTML in aspx) using AJAX. The example I found online demonstrated data display inside a div, but I'm unsure how to dynamically display my ow ...

datetime-local format changing after selection

In an ionic application running on an android system, there is a issue with the formatting of <input type='datetime-local'> inputs. After a user selects a date, the Start input is formatted differently than the Ende input. Attempts to use t ...

Error encountered after attempting to save with incorrect configuration settings for the resource

A portion of my code involves a service module that sends data using the POST method: //services.js var myServices = angular.module('myServices', ['ngResource']); myServices.factory('User', ['$resource', function($ ...

PHP implementation for a static header layout

I am interested in learning how to update content without refreshing the header. I have created a simple example below. Header.php <html> <head> </head> <body> <ul> <li><a href="index.php" ...

Node.js 'BLOB containing [object File]'

I am currently attempting to retrieve a BLOB from a request. The request object is created using FormData in Angular. const buffer = fs.readFileSync(fileFromRequest); The above code is resulting in an error: Error: ENOENT: no such file or directory, ope ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

Creating a custom if equals helper in Handlebars but encountering compilation errors

I have implemented a custom helper in Handlebars to create an if == "some string" type of helper. Here is the code for the helper: Handlebars.registerHelper('if_eq', function(a, b, opts) { if(a == b) // Or === depending on your needs ...

Incorporating a vanilla JS library (Pickr) into a NuxtJS page component

Recently, I've been experimenting with integrating the Pickr JS library (specifically from this link: [) into my NuxtJS project. To install it, I simply use NPM: npm install @simonwep/pickr In one of my NuxtJS pages - the create.vue page to be exac ...