Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/jantoniogc/CursoReact-Clima/llms.txt

Use this file to discover all available pages before exploring further.

All application state in Clima React App lives in a single component: App. Four useState hooks track form inputs, an API trigger flag, the raw API response, and an error condition. A single useEffect hook watches the trigger flag and executes the OpenWeatherMap API call whenever it flips to true. This keeps every side effect in one place and makes the data flow straightforward to trace.

State variables

1. busqueda — form inputs

const [busqueda, setBusqueda] = useState({
  ciudad: '',
  pais: ''
});
An object with two string fields that mirror the controlled inputs in Formulario. setBusqueda is passed as a prop so Formulario can update it on every keystroke using a computed property name ([e.target.name]: e.target.value).

2. consultar — API trigger flag

const [consultar, setConsultar] = useState(false);
A boolean that acts as a one-shot trigger. It starts as false and is set to true by Formulario when the user submits a valid form. The useEffect that performs the API call depends on this value, so flipping it to true causes the effect to re-run and fire the request.

3. resultado — API response

const [resultado, setResultado] = useState({});
Stores the raw JSON object returned by the OpenWeatherMap /data/2.5/weather endpoint. Initialized as an empty object so Clima can safely destructure it on the first render (it guards with if (!name) return null). After a successful call this object contains at minimum name (city string) and main ({ temp, temp_max, temp_min } in Kelvin).

4. error — API error flag

const [error, setError] = useState(false);
Set to true when the API response contains cod: '404' (city not found). Controls which component is shown in the results column: <Error> when true, <Clima> otherwise.

The useEffect and trigger pattern

useEffect(() => {
  const consultarApi = async () => {
    if (consultar) {
      const appId = '0ce99c97e4fe1a22354d272a43c40232';
      const url = `http://api.openweathermap.org/data/2.5/weather?q=${ciudad},${pais}&appid=${appId}`;
      const respuesta = await fetch(url);
      const resultado = await respuesta.json();

      if (resultado.cod === '404') {
        setError(true);
      } else {
        setError(false);
      }

      setResultado(resultado);
      setConsultar(false); // reset the trigger
    }
  }
  consultarApi();
  // eslint-disable-next-line
}, [consultar]);
The effect is declared with [consultar] as its dependency array, so React re-runs it whenever consultar changes. The inner guard if (consultar) prevents the effect from doing anything on the initial render (when consultar is false) or immediately after the reset. The reset at the end — setConsultar(false) — is what makes the pattern reusable: after the API call completes, consultar returns to false, so submitting the form again will flip it to true once more and trigger a fresh request.

Conditional rendering

After the useEffect runs, App decides which component to show in the results column:
let componente;
if (error) {
  componente = <Error mensaje="No hay resultados" />;
} else {
  componente = <Clima resultado={resultado} />;
}
<Clima> is always assigned when there is no API error, but it will render nothing on the first load because resultado is an empty object and Clima returns null when resultado.name is undefined.

Temperature conversion

Clima converts the raw Kelvin temperatures from the API to Celsius before displaying them:
const kelvin = 273.15;

parseFloat(main.temp - kelvin, 10).toFixed(2)       // current temperature
parseFloat(main.temp_max - kelvin, 10).toFixed(2)   // daily maximum
parseFloat(main.temp_min - kelvin, 10).toFixed(2)   // daily minimum
The subtraction of 273.15 is the standard Kelvin-to-Celsius offset. parseFloat is called with a radix argument of 10, though that argument has no effect on parseFloat (it is meaningful only for parseInt). .toFixed(2) formats the result to two decimal places.
For a larger app, the four state variables in App could be extracted into a React Context so deeply nested components can read weather data without prop-drilling. Libraries like Redux Toolkit or Zustand would be worth considering if the app grows to include multiple locations, historical data, or user preferences — each of which would add several more interdependent state slices.

Build docs developers (and LLMs) love