Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
Displaying "No results" message when manually fetching with React Query

So this is the first time I try to use React Query for manually fetching data, I'm building a simple Weather Forecast App and I did encounter a small "problem":

What I want is that when for some reason (for example, user inputs something crazy) data is not available, then display a "No results found" message.

The thing is the first time the component mounts, the React Query's data state will be undefined so I can't rely on that for displaying the No results message as it will show up even when someone is accessing for the first time to the app... Any ideas how can I display that message only when data is not available?

Here is my code:

import './App.css';
import Form from "./components/Form.jsx";
import { useQuery } from 'react-query';
import { useState } from 'react';
import { fetchData } from './api/httpRequest';
import Card from "./components/Card";


function App() {
  const [search, setSearch] = useState("");

  const { data: info, isFetching, isError, refetch } = useQuery("info",
    () => fetchData(search), {
    enabled: false,
    refetchOnWindowFocus: false,
  });


  console.log(info);

  return (

    <main className="App">
      <h1 className="app-title">Weather Forecast App</h1>
      <Form search={search} setSearch={setSearch} fetch={refetch} />
      {isFetching ? "Loading..." : isError ? "Error!" : !info ? "No results" : <Card forecast={info} />}
    </main>

  );
}

export default App;

These are the fetching functions:

import axios from "axios";

const API_WEATHER = "https://api.openweathermap.org/data/2.5/onecall?";
const API_WEATHER_EXCLUDE = "&exclude=minutely,hourly,alerts";
const API_COORDINATES = "http://api.positionstack.com/v1/forward?";

const getCoordinates = async (query) => {
    try {
        const response = await axios.get(API_COORDINATES + "access_key=" + process.env.REACT_APP_API_COORDS_KEY + "&query=" + query + "&limit=1");
        return response.data.data[0];
    }
    catch (error) {
        console.log(error);
    }
}

export const fetchData = async (query) => {
    try {
        const coords = await getCoordinates(query);
        const response = await axios.get(API_WEATHER + "lat=" + coords.latitude + "&lon=" + coords.longitude + API_WEATHER_EXCLUDE + "&appid=" + process.env.REACT_APP_API_WEATHER_KEY);
        return response.data;

    }
    catch (error) {
        console.log(error);
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can always use the status state (status === 'success') instead of isFetching, like stated in the documentations:

function Todos() {
   const { status, data, error } = useQuery('todos', fetchTodoList)
 
   if (status === 'loading') {
     return <span>Loading...</span>
   }
 
   if (status === 'error') {
     return <span>Error: {error.message}</span>
   }
 
   // also status === 'success', but "else" logic works, too
   return (
     <ul>
       {data.map(todo => (
         <li key={todo.id}>{todo.title}</li>
       ))}
     </ul>
   )
 }

I am not sure about your way of handling the returned data overall. I think it would be better to check the returned results not with !info because it can return a JSON data with other miscellaneous data along with am empty data for example.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda