useEffect hook wont run codeblock

Viewed 97

My useEffect hook dont seem to be running the block of code within its scope. Not exactly sure why, when i debug it the useEffect hook gets hit but the code within it never runs. I have placed a break point and it never lands on it.

    import {useState, useEffect} from "react";

const useApiResult = (request) => {
    const [results, setResults] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        loadData(request);
    }, [request]); 

    const loadData = async (request) => {
        console.log(request)
        try 
        {
            const response = await fetch(request);
            if(response.ok) {
                setResults(await response.json());
                setError(null);
            } else {
                setError(await response.text());
            } 
        } 
        catch (err) {
            setError(err);
        } 
    }
  
  return [results, error];
};

export default useApiResult;

Where I call useApiResult

import { useMemo } from 'react';
import { getPokemons } from '../requests';
import useApiResult  from '../customHooks/useApiResults';

const usePokemons = () => {
    const request = useMemo(() => getPokemons(), []);
    return useApiResult(request);
}

export default usePokemons;

getpokemons.js

export const BASE_URL = "https://pokeapi.co/api/v2";

const createUrl = (base, path) => `${base}${path}`;

export const getPokemons = () => [
  createUrl(BASE_URL, "/pokemon?offset=300&limit=10"),
  {
    method: "GET",
  }
];

enter image description here

enter image description here

1 Answers

My steps to catch issue:

  1. When I looked in your sandbox I noticed error: results is null

  2. I also found const [results, error] = usePokemons(); in PokemonList component, so I thought that this error is not necessary, I just removed it. Because you never used it in component.

  3. I still got results is null I just add condition render via &&. It looks like:

         results &&
           results.map((key, i) => (
    
  4. I got new error: results.map is not a function. It means that results is not array. When I saw at results I noticed that it has inside array with the same name. So I just add resuts after a dot.

     results &&
       results.results.map((key, i) => (
    

Here we go:)

Related