Search code examples
reactjsreduxredux-thunk

Fetching data from API - Unhandled Rejection (TypeError): Object(...) is not a function


I'm learning to work with API, redux and thunk now. I get:

Unhandled Rejection (TypeError): Object(...) is not a function

mistake.

my api.js is:

export const baseUrl = 'https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Coffee_/_Tea';

my receiptsAction.js is:

import axios from 'axios';
import {baseUrl} from '../api';

export const loadRecipes = () => async(dispatch) => {
    const drinksData = await axios.get(baseUrl());
    dispatch({
        type: "FETCH_RECIPES",
        payload: {
            drinks: drinksData.data,
        }
    })
}

my receiptsReducer.js is:

const initState = {
    drinks: {},
}

const receiptsReducer = (state=initState, action) => {
    switch(action.type) {
        case "FETCH_RECIPES":
            return {
                ...state, drinks: action.payload.drinks
            }
        default:
            return {...state}
    }
}

export default receiptsReducer;

my Home.js is:

import React, { useEffect } from 'react';
import {loadRecipes} from '../actions/receiptsAction';
import {useDispatch, useSelector} from 'react-redux';


const Home = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(loadRecipes())
    }, [dispatch]);

    return(
        <div>
            <p>Hello</p>
        </div>
    )
}

export default Home;

What I tried:

  1. Checked, if all semicolons are on the right places
  2. Checked, if APi is at all valid in App.js and it loaded information okay:
const coctailHandler = async () => {
  let url = "https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Coffee_/_Tea";
  const coctails = await axios.get(url);
  console.log(coctails.data.drinks);
}
  1. Checked, that the data came from API is an object. Also tried to give const initState = {drinks: {drinks: []},}. Also tried to write in action payload: {drinks: drinksData.data.drinks} with const initState = {drinks: []} in the reducer.

Will appreciate any help!


Solution

  • You are calling baseUrl as if it were a function, but it seems like it's just a string constant.

    await axios.get(baseUrl())
    

    That should be

    await axios.get(baseUrl)