State does not update and error : TypeError: dispatch is not a function shows up

Viewed 35

I am currently working on a personal project. I use an API to fetch news articles : I fetch latest news when the APP is rendering, not a single issue, the store gets all the datas needed and so on. But when I start want to search for a topic, nothing happens and I have this error in the browser console : "TypeError: dispatch is not a function"

Here's my action file where the error occurs

import { API_URL_BASE, API_KEY, FETCH_API } from "./constants";
import { ApiReducerInterface } from "./apiReducerInterface";
import axios from "axios";


export const fetchMainTopics = () => async (dispatch: any) => {
    try{
        const res = await axios.get(`${API_URL_BASE}top-headlines?country=fr&apiKey=${API_KEY}`);
        await dispatch(fetchAPI(res.data.articles));
    }
    catch(error) {
        console.log(error);
    }
}

export const searchTopics = (search: string) => async (dispatch: any) => {
    try{
        const res = await axios.get(`${API_URL_BASE}everything?q=${search}&apiKey=${API_KEY}`);
        await dispatch(fetchAPI(res.data.articles));
    }
    catch(error) {
        console.log(error);
    }
}

export const fetchAPI = (response: ApiReducerInterface[]) => ({
    type: FETCH_API,
    articles: response,
});

Here's my button to fetch the topic :

import { useState } from 'react';
import { searchTopics } from '../../store/apiReducer/action';

const Search: React.FC = () => {
    const [search, setSearch] = useState('');

    return(
        <div>
            <input onChange={(e) => setSearch(e.target.value)} placeholder="Search for a topic ..."/>
            <button onClick={searchTopics(search)}>Submit</button>
        </div>
    );
}

export default Search;

If anyone has an idea to help me out there please ? :D

Thanks for considering my request and happy coding :)

0 Answers
Related