Search code examples
javascriptreactjsaxiosantdfetch-api

TypeError: res is undefined when fetching data from dummyJson Api


  • Hey guys, i need some assistance, am fetching from dummy Json Api, using fech method, however am experiencing an error "TypeError: res is undefined" yet i see that i have defined it .
  • below is my useEffect hook which i use to get data.
import { getAllProducts } from "../API";

const Products = () => {
    const [items, setItems] = useState([]);

    useEffect(() => {
        getAllProducts()
            .then((res) => {
                setItems(res.data);
            })
            .catch(err => {
                console.log(err)
            })
    }, []);

    return (
        <List
            grid={{
                gutter: 16,
                xs: 1,
                sm: 2,
                md: 4,
                lg: 4,
                xl: 6,
                xxl: 3,
            }}
            dataSource={items}
            renderItem={(item) => (
                <List.Item>
                    <Card
                        key={item.id}
                        title={item.title}
                        cover={<Image src={item.thumbnail} />}
                    >
                    </Card>
                </List.Item>
            )}
        />
    );
}

export default Products;
  • Below is where i have made the api call from
export const getAllProducts = () => {
    return (
        fetch('https://dummyjson.com/products')
            .then(res => res.json())
            .then(console.log)
    )
}
  • any help is highly appreciated. i think am missing something out to display data
  • i can see in the console the products being fetched but when it comes to handling the response , i get res is not defined.

Solution

  • The issue is that your last .then callback in getAllProducts calls console.log with the data and then returns the return value of console.log, which is undefined. This becomes the first argument of the .then callback in your useEffect. If you want to add logging, you still have to return the data so it can be accessed in the next .then handler in the chain.

    return fetch('https://dummyjson.com/products')
        .then(res => res.json())
        .then(res => {
            console.log(res);
            return res;
        });
    

    In addition, the sample JSON returned has no data property. Its products property is an array though.

    setItems(res.products);